package controller

import (
	"netidhub-saas-be/app/database/entity"
	"netidhub-saas-be/app/module/approval_workflows/request"
	"netidhub-saas-be/app/module/approval_workflows/service"
	"netidhub-saas-be/utils/paginator"
	"strconv"

	"github.com/gofiber/fiber/v2"
	"github.com/rs/zerolog"

	utilRes "netidhub-saas-be/utils/response"
	utilVal "netidhub-saas-be/utils/validator"
)

type approvalWorkflowsController struct {
	approvalWorkflowsService service.ApprovalWorkflowsService
	Log                      zerolog.Logger
}

type ApprovalWorkflowsController 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
	GetDefault(c *fiber.Ctx) error
	SetDefault(c *fiber.Ctx) error
	Activate(c *fiber.Ctx) error
	Deactivate(c *fiber.Ctx) error
	GetWithSteps(c *fiber.Ctx) error
	SaveWithSteps(c *fiber.Ctx) error
	UpdateWithSteps(c *fiber.Ctx) error
}

func NewApprovalWorkflowsController(approvalWorkflowsService service.ApprovalWorkflowsService, log zerolog.Logger) ApprovalWorkflowsController {
	return &approvalWorkflowsController{
		approvalWorkflowsService: approvalWorkflowsService,
		Log:                      log,
	}
}

// All ApprovalWorkflows
// @Summary      Get all ApprovalWorkflows
// @Description  API for getting all ApprovalWorkflows
// @Tags         ApprovalWorkflows
// @Security     Bearer
// @Param        Authorization header string true "Insert the Authorization"
// @Param        req query request.ApprovalWorkflowsQueryRequest 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       /approval-workflows [get]
func (_i *approvalWorkflowsController) All(c *fiber.Ctx) error {
	paginate, err := paginator.Paginate(c)
	if err != nil {
		return err
	}

	reqContext := request.ApprovalWorkflowsQueryRequestContext{
		Name:        c.Query("name"),
		Description: c.Query("description"),
		IsActive:    c.Query("isActive"),
		IsDefault:   c.Query("isDefault"),
	}
	req := reqContext.ToParamRequest()
	req.Pagination = paginate

	// Get authToken from context
	authToken := c.Get("Authorization")

	_i.Log.Info().Interface("authToken", authToken).Msg("")

	approvalWorkflowsData, paging, err := _i.approvalWorkflowsService.GetAll(authToken, req)
	if err != nil {
		return err
	}

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

// Show ApprovalWorkflows
// @Summary      Get one ApprovalWorkflows
// @Description  API for getting one ApprovalWorkflows
// @Tags         ApprovalWorkflows
// @Security     Bearer
// @Param        Authorization header string true "Insert the Authorization"
// @Param        id path int true "ApprovalWorkflows ID"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /approval-workflows/{id} [get]
func (_i *approvalWorkflowsController) Show(c *fiber.Ctx) error {
	id, err := strconv.Atoi(c.Params("id"))
	if err != nil {
		return utilRes.ErrorBadRequest(c, "Invalid ID format")
	}

	// Get authToken from context
	authToken := c.Get("Authorization")

	approvalWorkflowsData, err := _i.approvalWorkflowsService.FindOne(authToken, uint(id))
	if err != nil {
		return err
	}

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

// Save ApprovalWorkflows
// @Summary      Save ApprovalWorkflows
// @Description  API for saving ApprovalWorkflows
// @Tags         ApprovalWorkflows
// @Security     Bearer
// @Param        Authorization header string true "Insert the Authorization"
// @Param 	     payload body request.ApprovalWorkflowsCreateRequest true "Required payload"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /approval-workflows [post]
func (_i *approvalWorkflowsController) Save(c *fiber.Ctx) error {
	req := new(request.ApprovalWorkflowsCreateRequest)
	if err := utilVal.ParseAndValidate(c, req); err != nil {
		return err
	}

	// Get authToken from context
	authToken := c.Get("Authorization")

	// Convert request to entity
	workflow := req.ToEntity()
	steps := req.ToStepsEntity()

	approvalWorkflowsData, err := _i.approvalWorkflowsService.Create(authToken, workflow, steps)
	if err != nil {
		return err
	}

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

// Update ApprovalWorkflows
// @Summary      Update ApprovalWorkflows
// @Description  API for updating ApprovalWorkflows
// @Tags         ApprovalWorkflows
// @Security     Bearer
// @Param        Authorization header string true "Insert the Authorization"
// @Param        id path int true "ApprovalWorkflows ID"
// @Param 	     payload body request.ApprovalWorkflowsUpdateRequest true "Required payload"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /approval-workflows/{id} [put]
func (_i *approvalWorkflowsController) Update(c *fiber.Ctx) error {
	id, err := strconv.Atoi(c.Params("id"))
	if err != nil {
		return utilRes.ErrorBadRequest(c, "Invalid ID format")
	}

	req := new(request.ApprovalWorkflowsUpdateRequest)
	if err := utilVal.ParseAndValidate(c, req); err != nil {
		return err
	}

	// Get authToken from context
	authToken := c.Get("Authorization")

	// Convert request to entity
	workflow := req.ToEntity()

	err = _i.approvalWorkflowsService.Update(authToken, uint(id), workflow)
	if err != nil {
		return err
	}

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

// Delete ApprovalWorkflows
// @Summary      Delete ApprovalWorkflows
// @Description  API for deleting ApprovalWorkflows
// @Tags         ApprovalWorkflows
// @Security     Bearer
// @Param        Authorization header string true "Insert the Authorization"
// @Param        id path int true "ApprovalWorkflows ID"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /approval-workflows/{id} [delete]
func (_i *approvalWorkflowsController) Delete(c *fiber.Ctx) error {
	id, err := strconv.Atoi(c.Params("id"))
	if err != nil {
		return utilRes.ErrorBadRequest(c, "Invalid ID format")
	}

	// Get authToken from context
	authToken := c.Get("Authorization")

	err = _i.approvalWorkflowsService.Delete(authToken, uint(id))
	if err != nil {
		return err
	}

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

// GetDefault ApprovalWorkflows
// @Summary      Get default ApprovalWorkflows
// @Description  API for getting default ApprovalWorkflows
// @Tags         ApprovalWorkflows
// @Security     Bearer
// @Param        Authorization header string true "Insert the Authorization"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /approval-workflows/default [get]
func (_i *approvalWorkflowsController) GetDefault(c *fiber.Ctx) error {
	// Get authToken from context
	authToken := c.Get("Authorization")

	approvalWorkflowsData, err := _i.approvalWorkflowsService.GetDefault(authToken)
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"Default ApprovalWorkflows successfully retrieved"},
		Data:     approvalWorkflowsData,
	})
}

// SetDefault ApprovalWorkflows
// @Summary      Set default ApprovalWorkflows
// @Description  API for setting default ApprovalWorkflows
// @Tags         ApprovalWorkflows
// @Security     Bearer
// @Param        Authorization header string true "Insert the Authorization"
// @Param        id path int true "ApprovalWorkflows ID"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /approval-workflows/{id}/set-default [put]
func (_i *approvalWorkflowsController) SetDefault(c *fiber.Ctx) error {
	id, err := strconv.Atoi(c.Params("id"))
	if err != nil {
		return utilRes.ErrorBadRequest(c, "Invalid ID format")
	}

	// Get authToken from context
	authToken := c.Get("Authorization")

	err = _i.approvalWorkflowsService.SetDefault(authToken, uint(id))
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"ApprovalWorkflows successfully set as default"},
	})
}

// Activate ApprovalWorkflows
// @Summary      Activate ApprovalWorkflows
// @Description  API for activating ApprovalWorkflows
// @Tags         ApprovalWorkflows
// @Security     Bearer
// @Param        Authorization header string true "Insert the Authorization"
// @Param        id path int true "ApprovalWorkflows ID"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /approval-workflows/{id}/activate [put]
func (_i *approvalWorkflowsController) Activate(c *fiber.Ctx) error {
	id, err := strconv.Atoi(c.Params("id"))
	if err != nil {
		return utilRes.ErrorBadRequest(c, "Invalid ID format")
	}

	// Get authToken from context
	authToken := c.Get("Authorization")

	err = _i.approvalWorkflowsService.ActivateWorkflow(authToken, uint(id))
	if err != nil {
		return err
	}

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

// Deactivate ApprovalWorkflows
// @Summary      Deactivate ApprovalWorkflows
// @Description  API for deactivating ApprovalWorkflows
// @Tags         ApprovalWorkflows
// @Security     Bearer
// @Param        Authorization header string true "Insert the Authorization"
// @Param        id path int true "ApprovalWorkflows ID"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /approval-workflows/{id}/deactivate [put]
func (_i *approvalWorkflowsController) Deactivate(c *fiber.Ctx) error {
	id, err := strconv.Atoi(c.Params("id"))
	if err != nil {
		return utilRes.ErrorBadRequest(c, "Invalid ID format")
	}

	// Get authToken from context
	authToken := c.Get("Authorization")

	err = _i.approvalWorkflowsService.DeactivateWorkflow(authToken, uint(id))
	if err != nil {
		return err
	}

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

// GetWithSteps ApprovalWorkflows
// @Summary      Get ApprovalWorkflows with steps
// @Description  API for getting ApprovalWorkflows with steps
// @Tags         ApprovalWorkflows
// @Security     Bearer
// @Param        Authorization header string true "Insert the Authorization"
// @Param        id path int true "ApprovalWorkflows ID"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /approval-workflows/{id}/with-steps [get]
func (_i *approvalWorkflowsController) GetWithSteps(c *fiber.Ctx) error {
	id, err := strconv.Atoi(c.Params("id"))
	if err != nil {
		return utilRes.ErrorBadRequest(c, "Invalid ID format")
	}

	// Get authToken from context
	authToken := c.Get("Authorization")

	workflowData, stepsData, err := _i.approvalWorkflowsService.GetWorkflowWithSteps(authToken, uint(id))
	if err != nil {
		return err
	}

	// Combine workflow and steps data
	responseData := map[string]interface{}{
		"workflow": workflowData,
		"steps":    stepsData,
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"ApprovalWorkflows with steps successfully retrieved"},
		Data:     responseData,
	})
}

// SaveWithSteps ApprovalWorkflows
// @Summary      Create ApprovalWorkflows with steps
// @Description  API for creating ApprovalWorkflows with steps
// @Tags         ApprovalWorkflows
// @Security     Bearer
// @Param        Authorization header string true "Insert the Authorization"
// @Param        req body request.ApprovalWorkflowsWithStepsCreateRequest true "ApprovalWorkflows with steps data"
// @Success      201  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /approval-workflows/with-steps [post]
func (_i *approvalWorkflowsController) SaveWithSteps(c *fiber.Ctx) error {
	req := new(request.ApprovalWorkflowsWithStepsCreateRequest)
	if err := utilVal.ParseAndValidate(c, req); err != nil {
		return err
	}

	// Get authToken from context
	authToken := c.Get("Authorization")

	// Convert request to entities
	workflow := req.ToEntity()
	steps := req.ToStepsEntity()

	approvalWorkflowsData, err := _i.approvalWorkflowsService.CreateWorkflowWithSteps(authToken, workflow, steps)
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"ApprovalWorkflows with steps successfully created"},
		Data:     approvalWorkflowsData,
	})
}

// UpdateWithSteps ApprovalWorkflows
// @Summary      Update ApprovalWorkflows with steps
// @Description  API for updating ApprovalWorkflows with steps
// @Tags         ApprovalWorkflows
// @Security     Bearer
// @Param        Authorization header string true "Insert the Authorization"
// @Param        id path int true "ApprovalWorkflows ID"
// @Param        req body request.ApprovalWorkflowsWithStepsUpdateRequest true "ApprovalWorkflows with steps data"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /approval-workflows/{id}/with-steps [put]
func (_i *approvalWorkflowsController) UpdateWithSteps(c *fiber.Ctx) error {
	id, err := strconv.Atoi(c.Params("id"))
	if err != nil {
		return utilRes.ErrorBadRequest(c, "Invalid ID format")
	}

	req := new(request.ApprovalWorkflowsWithStepsUpdateRequest)
	if err := utilVal.ParseAndValidate(c, req); err != nil {
		return err
	}

	// Get authToken from context
	authToken := c.Get("Authorization")

	// Convert request to entities
	workflow := &entity.ApprovalWorkflows{
		Name:        req.Name,
		Description: &req.Description,
		IsActive:    req.IsActive,
		IsDefault:   req.IsDefault,
	}

	steps := make([]*entity.ApprovalWorkflowSteps, len(req.Steps))
	for i, stepReq := range req.Steps {
		steps[i] = stepReq.ToEntity(uint(id))
	}

	err = _i.approvalWorkflowsService.UpdateWorkflowWithSteps(authToken, uint(id), workflow, steps)
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"ApprovalWorkflows with steps successfully updated"},
	})
}
