package province

import (
	"cargo-erp-backend/internal/handlers/dto"
	provinceimporter "cargo-erp-backend/internal/importers/province"
	"cargo-erp-backend/internal/usecases"
	"cargo-erp-backend/pkg/helpers"
	"cargo-erp-backend/pkg/importer"
	"cargo-erp-backend/pkg/response"
	"net/http"

	"github.com/gin-gonic/gin"
)

type ProvinceHandlerInterface interface {
	Router()
}

type ProvinceHandler struct {
	Helper helpers.HelperInterface
	Group  *gin.RouterGroup
}

func NewProvinceHandler(helper helpers.HelperInterface, g *gin.RouterGroup) ProvinceHandlerInterface {
	return &ProvinceHandler{Helper: helper, Group: g}
}

func (h *ProvinceHandler) Router() {
	r := h.Group.Group("provinces")
	{
		r.GET("/", h.GetAll)
		r.POST("/list", h.GetList)
		r.GET("/:id", h.GetByID)
		r.POST("/", h.Create)
		r.PUT("/:id", h.Update)
		r.DELETE("/:id", h.Delete)
		r.GET("/template", h.Template)
		r.POST("/import", h.Import)
		r.POST("/import/stop", h.ImportStop)
		r.GET("/import/status/:jobId", h.ImportStatus)
	}
}

func (h *ProvinceHandler) GetAll(c *gin.Context) {
	userid, err := h.Helper.GetAuthInfo(c.GetString("auth"))
	if err != nil {
		response.Error(c, http.StatusUnauthorized, err.Error())
		return
	}
	var req dto.ProvinceFilterAllRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		response.Error(c, http.StatusBadRequest, err.Error())
		return
	}
	u := usecases.NewProvinceUsecase(h.Helper, *userid)
	provinces, _, err := u.GetAll(req)
	if err != nil {
		response.Error(c, http.StatusInternalServerError, err.Error())
		return
	}
	var responseDTO = make([]dto.CreateProvinceResponse, 0)
	for _, v := range provinces {
		var DTO dto.CreateProvinceResponse
		h.Helper.MapStructToStruct(v, "json", &DTO, "json")
		responseDTO = append(responseDTO, DTO)
	}
	response.Success(c, responseDTO)
}

func (h *ProvinceHandler) GetList(c *gin.Context) {
	userid, err := h.Helper.GetAuthInfo(c.GetString("auth"))
	if err != nil {
		response.Error(c, http.StatusUnauthorized, err.Error())
		return
	}

	var req dto.DataTableRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, http.StatusBadRequest, "Request Format request invalid")
		return
	}
	u := usecases.NewProvinceUsecase(h.Helper, *userid)
	res, err := u.GetList(req)
	if err != nil {
		response.Error(c, http.StatusInternalServerError, err.Error())
		return
	}
	response.Success(c, res)
	return
}

func (h *ProvinceHandler) GetByID(c *gin.Context) {
	userid, err := h.Helper.GetAuthInfo(c.GetString("auth"))
	if err != nil {
		response.Error(c, http.StatusUnauthorized, err.Error())
		return
	}
	id := c.Param("id")

	u := usecases.NewProvinceUsecase(h.Helper, *userid)
	province, err := u.GetByID(id)
	if err != nil {
		response.Error(c, http.StatusNotFound, "province not found")
		return
	}

	response.Success(c, province)
}

func (h *ProvinceHandler) Create(c *gin.Context) {
	var req dto.CreateProvinceRequest
	if err := c.BindJSON(&req); err != nil {
		response.Error(c, http.StatusBadRequest, err.Error())
		return
	}
	userid, err := h.Helper.GetAuthInfo(c.GetString("auth"))
	if err != nil {
		response.Error(c, http.StatusUnauthorized, err.Error())
		return
	}
	var merchantid *string = nil
	if userid.UsersRole_Relation == nil || userid.UsersRole_Relation.RoleKey != "SPM" {
		merchantid = userid.MerchantID
	}
	createdBy := userid.ID

	u := usecases.NewProvinceUsecase(h.Helper, *userid)
	province, err := u.Create(req.Name, createdBy, merchantid)
	if err != nil {
		response.Error(c, http.StatusInternalServerError, err.Error())
		return
	}
	var responseDTO dto.CreateProvinceResponse
	h.Helper.MapStructToStruct(province, "json", &responseDTO, "json")
	response.Created(c, responseDTO)
}

func (h *ProvinceHandler) Update(c *gin.Context) {
	id := c.Param("id")

	var req dto.UpdateProvinceRequest
	if err := c.BindJSON(&req); err != nil {
		response.Error(c, http.StatusBadRequest, err.Error())
		return
	}
	userid, err := h.Helper.GetAuthInfo(c.GetString("auth"))
	if err != nil {
		response.Error(c, http.StatusUnauthorized, err.Error())
		return
	}
	updatedBy := userid.ID

	u := usecases.NewProvinceUsecase(h.Helper, *userid)
	province, err := u.Update(id, req.Name, updatedBy)
	if err != nil {
		response.Error(c, http.StatusInternalServerError, err.Error())
		return
	}
	var responseDTO dto.CreateProvinceResponse
	h.Helper.MapStructToStruct(province, "json", &responseDTO, "json")
	response.Success(c, responseDTO)
}

func (h *ProvinceHandler) Delete(c *gin.Context) {
	userid, err := h.Helper.GetAuthInfo(c.GetString("auth"))
	if err != nil {
		response.Error(c, http.StatusUnauthorized, err.Error())
		return
	}
	id := c.Param("id")
	u := usecases.NewProvinceUsecase(h.Helper, *userid)
	if err := u.Delete(id); err != nil {
		response.Error(c, http.StatusInternalServerError, err.Error())
		return
	}

	response.Success(c, map[string]interface{}{"message": "province deleted"})
}

func (h *ProvinceHandler) Template(c *gin.Context) {
	userid, err := h.Helper.GetAuthInfo(c.GetString("auth"))
	if err != nil {
		response.Error(c, http.StatusUnauthorized, err.Error())
		return
	}
	handler := provinceimporter.NewProvinceImportHandler(*userid)
	imp := importer.NewImporter(h.Helper, handler)
	imp.ServeTemplate(c.Writer)
}

func (h *ProvinceHandler) Import(c *gin.Context) {
	userid, err := h.Helper.GetAuthInfo(c.GetString("auth"))
	if err != nil {
		response.Error(c, http.StatusUnauthorized, err.Error())
		return
	}

	file, header, err := c.Request.FormFile("file")
	if err != nil {
		response.Error(c, http.StatusBadRequest, "File is required")
		return
	}
	defer file.Close()

	handler := provinceimporter.NewProvinceImportHandler(*userid)
	imp := importer.NewImporter(h.Helper, handler)

	result, err := imp.Process(file, userid.ID, header.Filename)
	if err != nil {
		response.Error(c, http.StatusBadRequest, err.Error())
		return
	}

	var importLogs []dto.ImportLog
	for _, l := range result.Logs {
		importLogs = append(importLogs, dto.ImportLog{
			Row:     l.Row,
			Status:  l.Status,
			Data:    l.Data,
			Message: l.Message,
		})
	}

	response.Success(c, dto.ImportProvinceResponse{
		JobID:     result.JobID,
		TotalRows: result.TotalRows,
		Imported:  result.Imported,
		Skipped:   result.Skipped,
		Logs:      importLogs,
		Errors:    result.Errors,
		IsAsync:   result.IsAsync,
		Message:   result.Message,
	})
}

func (h *ProvinceHandler) ImportStatus(c *gin.Context) {
	userid, err := h.Helper.GetAuthInfo(c.GetString("auth"))
	if err != nil {
		response.Error(c, http.StatusUnauthorized, err.Error())
		return
	}
	jobId := c.Param("jobId")

	handler := provinceimporter.NewProvinceImportHandler(*userid)
	imp := importer.NewImporter(h.Helper, handler)

	job, logs, err := imp.GetJobStatus(jobId)
	if err != nil {
		response.Error(c, http.StatusNotFound, "Job not found")
		return
	}

	response.Success(c, map[string]interface{}{
		"job":  job,
		"logs": logs,
	})
}

func (h *ProvinceHandler) ImportStop(c *gin.Context) {
	userid, err := h.Helper.GetAuthInfo(c.GetString("auth"))
	if err != nil {
		response.Error(c, http.StatusUnauthorized, err.Error())
		return
	}

	var req dto.StopImportRequest
	if err := c.BindJSON(&req); err != nil {
		response.Error(c, http.StatusBadRequest, "job_id is required")
		return
	}

	handler := provinceimporter.NewProvinceImportHandler(*userid)
	imp := importer.NewImporter(h.Helper, handler)

	if err := imp.StopJob(req.JobID); err != nil {
		response.Error(c, http.StatusBadRequest, err.Error())
		return
	}

	response.Success(c, map[string]interface{}{"message": "Job stopped"})
}
