package controller

import (
	"encoding/json"
	"jaecoo-be/app/module/sales_agents/request"
	"jaecoo-be/app/module/sales_agents/service"
	"jaecoo-be/utils/paginator"
	"strconv"

	"github.com/gofiber/fiber/v2"

	utilRes "jaecoo-be/utils/response"
)

type salesAgentsController struct {
	salesAgentsService service.SalesAgentsService
}

type SalesAgentsController interface {
	All(c *fiber.Ctx) error
	Show(c *fiber.Ctx) error
	Save(c *fiber.Ctx) error
	Update(c *fiber.Ctx) error
	Delete(c *fiber.Ctx) error
	Viewer(c *fiber.Ctx) error
}

func NewSalesAgentsController(salesAgentsService service.SalesAgentsService) SalesAgentsController {
	return &salesAgentsController{
		salesAgentsService: salesAgentsService,
	}
}

// All SalesAgents
// @Summary      Get all SalesAgents
// @Description  API for getting all SalesAgents
// @Tags         SalesAgents
// @Security     Bearer
// @Param        X-Client-Key header string true "Insert the X-Client-Key"
// @Param 	     req query request.SalesAgentsQueryRequestContext false "query parameters"
// @Param 	     req query paginator.Pagination false "pagination parameters"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /sales-agents [get]
func (_i *salesAgentsController) All(c *fiber.Ctx) error {
	paginate, err := paginator.Paginate(c)
	if err != nil {
		return err
	}

	reqContext := request.SalesAgentsQueryRequestContext{
		Name:      c.Query("name"),
		JobTitle:  c.Query("job_title"),
		AgentType: c.Query("agent_type"),
	}
	req := reqContext.ToParamRequest()
	req.Pagination = paginate

	agentsData, paging, err := _i.salesAgentsService.GetAll(req)
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"SalesAgents list successfully retrieved"},
		Data:     agentsData,
		Meta:     paging,
	})
}

// Show SalesAgent
// @Summary      Get SalesAgent by ID
// @Description  API for getting SalesAgent by ID
// @Tags         SalesAgents
// @Security     Bearer
// @Param        X-Client-Key header string true "Insert the X-Client-Key"
// @Param        id path int true "SalesAgent ID"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /sales-agents/{id} [get]
func (_i *salesAgentsController) Show(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 0)
	if err != nil {
		return err
	}

	agentData, err := _i.salesAgentsService.GetOne(uint(id))
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"SalesAgent successfully retrieved"},
		Data:     agentData,
	})
}

// Save SalesAgent
// @Summary      Create SalesAgent
// @Description  API for creating SalesAgent with file upload
// @Tags         SalesAgents
// @Security     Bearer
// @Param        X-Client-Key header string true "Insert the X-Client-Key"
// @Param        file formData file false "Upload file"
// @Param        name formData string true "SalesAgent name"
// @Param        job_title formData string false "SalesAgent job title"
// @Param        phone formData string false "SalesAgent phone"
// @Param        agent_type formData string false "SalesAgent agent type (JSON array)"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /sales-agents [post]
func (_i *salesAgentsController) Save(c *fiber.Ctx) error {
	// Parse multipart form
	form, err := c.MultipartForm()
	if err != nil {
		return utilRes.Resp(c, utilRes.Response{
			Success:  false,
			Messages: utilRes.Messages{"Failed to parse form data"},
		})
	}

	// Extract form values
	req := request.SalesAgentsCreateRequest{
		Name: c.FormValue("name"),
	}

	if jobTitle := c.FormValue("job_title"); jobTitle != "" {
		req.JobTitle = &jobTitle
	}

	if phone := c.FormValue("phone"); phone != "" {
		req.Phone = &phone
	}

	// Handle agent_type (JSON array string)
	if agentTypeStr := c.FormValue("agent_type"); agentTypeStr != "" {
		var agentType []string
		if err := json.Unmarshal([]byte(agentTypeStr), &agentType); err == nil {
			req.AgentType = agentType
		}
	}

	// Validate required fields
	if req.Name == "" {
		return utilRes.Resp(c, utilRes.Response{
			Success:  false,
			Messages: utilRes.Messages{"Name is required"},
		})
	}

	// Check if file is uploaded
	if len(form.File["file"]) > 0 {
		// File will be handled in service
	}

	dataResult, err := _i.salesAgentsService.Create(c, req)
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"SalesAgent successfully created"},
		Data:     dataResult,
	})
}

// Update SalesAgent
// @Summary      Update SalesAgent
// @Description  API for updating SalesAgent with file upload
// @Tags         SalesAgents
// @Security     Bearer
// @Param        X-Client-Key header string true "Insert the X-Client-Key"
// @Param        id path int true "SalesAgent ID"
// @Param        file formData file false "Upload file"
// @Param        name formData string false "SalesAgent name"
// @Param        job_title formData string false "SalesAgent job title"
// @Param        phone formData string false "SalesAgent phone"
// @Param        agent_type formData string false "SalesAgent agent type (JSON array)"
// @Param        is_active formData bool false "SalesAgent is_active"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /sales-agents/{id} [put]
func (_i *salesAgentsController) Update(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 0)
	if err != nil {
		return err
	}

	// Parse multipart form
	form, err := c.MultipartForm()
	if err != nil {
		return utilRes.Resp(c, utilRes.Response{
			Success:  false,
			Messages: utilRes.Messages{"Failed to parse form data"},
		})
	}

	// Extract form values
	req := request.SalesAgentsUpdateRequest{}

	if name := c.FormValue("name"); name != "" {
		req.Name = &name
	}

	if jobTitle := c.FormValue("job_title"); jobTitle != "" {
		req.JobTitle = &jobTitle
	}

	if phone := c.FormValue("phone"); phone != "" {
		req.Phone = &phone
	}

	// Handle agent_type (JSON array string)
	if agentTypeStr := c.FormValue("agent_type"); agentTypeStr != "" {
		var agentType []string
		if err := json.Unmarshal([]byte(agentTypeStr), &agentType); err == nil {
			req.AgentType = agentType
		}
	}

	if isActiveStr := c.FormValue("is_active"); isActiveStr != "" {
		isActive := isActiveStr == "true" || isActiveStr == "1"
		req.IsActive = &isActive
	}

	// Check if file is uploaded
	if len(form.File["file"]) > 0 {
		// File will be handled in service
	}

	dataResult, err := _i.salesAgentsService.Update(c, uint(id), req)
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"SalesAgent successfully updated"},
		Data:     dataResult,
	})
}

// Delete SalesAgent
// @Summary      Delete SalesAgent
// @Description  API for deleting SalesAgent (soft delete)
// @Tags         SalesAgents
// @Security     Bearer
// @Param        X-Client-Key header string true "Insert the X-Client-Key"
// @Param        id path int true "SalesAgent ID"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /sales-agents/{id} [delete]
func (_i *salesAgentsController) Delete(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 0)
	if err != nil {
		return err
	}

	err = _i.salesAgentsService.Delete(uint(id))
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"SalesAgent successfully deleted"},
	})
}

// Viewer SalesAgent
// @Summary      Viewer SalesAgent
// @Description  API for viewing SalesAgent profile picture file
// @Tags         SalesAgents
// @Security     Bearer
// @Param        X-Client-Key header string true "Insert the X-Client-Key"
// @Param        filename path string true "SalesAgent File Name (e.g., user_277788.png)"
// @Success      200  {file}  file
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /sales-agents/viewer/{filename} [get]
func (_i *salesAgentsController) Viewer(c *fiber.Ctx) error {
	return _i.salesAgentsService.Viewer(c)
}

