package controller

import (
	"jaecoo-be/app/module/users/request"
	"jaecoo-be/app/module/users/service"
	"jaecoo-be/utils/paginator"
	"strconv"

	"github.com/gofiber/fiber/v2"
	_ "github.com/gofiber/fiber/v2"

	utilRes "jaecoo-be/utils/response"
	utilVal "jaecoo-be/utils/validator"
)

type usersController struct {
	usersService service.UsersService
}

type UsersController interface {
	All(c *fiber.Ctx) error
	Show(c *fiber.Ctx) error
	ShowByUsername(c *fiber.Ctx) error
	ShowInfo(c *fiber.Ctx) error
	Save(c *fiber.Ctx) error
	Update(c *fiber.Ctx) error
	Login(c *fiber.Ctx) error
	ParetoLogin(c *fiber.Ctx) error
	Delete(c *fiber.Ctx) error
	SavePassword(c *fiber.Ctx) error
	ResetPassword(c *fiber.Ctx) error
	ForgotPassword(c *fiber.Ctx) error
	OtpRequest(c *fiber.Ctx) error
	OtpValidation(c *fiber.Ctx) error
	EmailValidation(c *fiber.Ctx) error
	SetupEmail(c *fiber.Ctx) error
}

func NewUsersController(usersService service.UsersService) UsersController {
	return &usersController{
		usersService: usersService,
	}
}

// All Users
// @Summary      Get all Users
// @Description  API for getting all Users
// @Tags         Users
// @Security     Bearer
// @Param        Authorization header string false "Insert your access token" default(Bearer <Add access token here>)
// @Param 	     req query request.UsersQueryRequest 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       /users [get]
func (_i *usersController) All(c *fiber.Ctx) error {
	paginate, err := paginator.Paginate(c)
	if err != nil {
		return err
	}

	reqContext := request.UsersQueryRequestContext{
		Username:            c.Query("username"),
		Email:               c.Query("email"),
		Fullname:            c.Query("fullname"),
		PhoneNumber:         c.Query("phoneNumber"),
		WorkType:            c.Query("workType"),
		GenderType:          c.Query("genderType"),
		IdentityType:        c.Query("identityType"),
		IdentityGroup:       c.Query("identityGroup"),
		IdentityGroupNumber: c.Query("identityGroupNumber"),
		IdentityNumber:      c.Query("identityNumber"),
		UserRoleId:          c.Query("userRoleId"),
		StatusId:            c.Query("statusId"),
	}
	req := reqContext.ToParamRequest()
	req.Pagination = paginate

	usersData, paging, err := _i.usersService.All(req)
	if err != nil {
		return err
	}

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

// Show Users
// @Summary      Get one Users
// @Description  API for getting one Users
// @Tags         Users
// @Security     Bearer
// @Param        Authorization header string false "Insert your access token" default(Bearer <Add access token here>)
// @Param        id path int true "Users ID"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /users/detail/{id} [get]
func (_i *usersController) Show(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 0)
	if err != nil {
		return err
	}

	usersData, err := _i.usersService.Show(uint(id))
	if err != nil {
		return err
	}

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

// ShowByUsername Users
// @Summary      Get one Users
// @Description  API for getting one Users
// @Tags         Users
// @Security     Bearer
// @Param        username path string true "Username"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /users/username/{username} [get]
func (_i *usersController) ShowByUsername(c *fiber.Ctx) error {
	username := c.Params("username")

	usersData, err := _i.usersService.ShowByUsername(username)
	if err != nil {
		return err
	}

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

// ShowInfo Users
// @Summary      ShowInfo Users
// @Description  API for ShowUserInfo
// @Tags         Users
// @Security     Bearer
// @Param        Authorization header string false "Insert your access token" default(Bearer <Add access token here>)
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /users/info [get]
func (_i *usersController) ShowInfo(c *fiber.Ctx) error {
	authToken := c.Get("Authorization")

	dataResult, err := _i.usersService.ShowUserInfo(authToken)
	if err != nil {
		return err
	}

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

// Save Users
// @Summary      Create Users
// @Description  API for create Users
// @Tags         Users
// @Security     Bearer
// @Param        X-Csrf-Token header string true "Insert the X-Csrf-Token"
// @Param        Authorization header string false "Insert your access token" default(Bearer <Add access token here>)
// @Param 	     payload body request.UsersCreateRequest true "Required payload"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /users [post]
func (_i *usersController) Save(c *fiber.Ctx) error {
	req := new(request.UsersCreateRequest)
	if err := utilVal.ParseAndValidate(c, req); err != nil {
		return err
	}

	authToken := c.Get("Authorization")

	dataResult, err := _i.usersService.Save(*req, authToken)
	if err != nil {
		return err
	}

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

// Update Users
// @Summary      update Users
// @Description  API for update Users
// @Tags         Users
// @Security     Bearer
// @Param        X-Csrf-Token header string true "Insert the X-Csrf-Token"
// @Param        Authorization header string false "Insert your access token" default(Bearer <Add access token here>)
// @Param        id path int true "Users ID"
// @Param 	     payload body request.UsersUpdateRequest true "Required payload"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /users/{id} [put]
func (_i *usersController) Update(c *fiber.Ctx) error {
	id, err := strconv.ParseUint(c.Params("id"), 10, 0)
	if err != nil {
		return err
	}

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

	err = _i.usersService.Update(uint(id), *req)
	if err != nil {
		return err
	}

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

// Login Users
// @Summary      Login Users
// @Description  API for Login Users
// @Tags         Users
// @Security     Bearer
// @Param        X-Csrf-Token header string true "Insert the X-Csrf-Token"
// @Param 	     payload body request.UserLogin true "Required payload"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /users/login [post]
func (_i *usersController) Login(c *fiber.Ctx) error {
	req := new(request.UserLogin)
	if err := utilVal.ParseAndValidate(c, req); err != nil {
		return err
	}

	loginResponse, err := _i.usersService.Login(*req)
	if err != nil {
		return utilRes.Resp(c, utilRes.Response{
			Success:  false,
			Code:     401,
			Messages: utilRes.Messages{err.Error()},
		})
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"Users successfully login"},
		Data:     loginResponse,
	})
}

// ParetoLogin Users
// @Summary      ParetoLogin Users
// @Description  API for ParetoLogin Users
// @Tags         Users
// @Security     Bearer
// @Param        X-Csrf-Token header string true "Insert the X-Csrf-Token"
// @Param 	     payload body request.UserLogin true "Required payload"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /users/pareto-login [post]
func (_i *usersController) ParetoLogin(c *fiber.Ctx) error {
	req := new(request.UserLogin)
	if err := utilVal.ParseAndValidate(c, req); err != nil {
		return err
	}

	loginResponse, err := _i.usersService.ParetoLogin(*req)
	if err != nil {
		return utilRes.Resp(c, utilRes.Response{
			Success:  false,
			Code:     401,
			Messages: utilRes.Messages{err.Error()},
		})
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"Users successfully login"},
		Data:     loginResponse,
	})
}

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

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

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

// SavePassword Users
// @Summary      SavePassword Users
// @Description  API for SavePassword Users
// @Tags         Users
// @Security     Bearer
// @Param        X-Csrf-Token header string true "Insert the X-Csrf-Token"
// @Param        Authorization header string false "Insert your access token" default(Bearer <Add access token here>)
// @Param 	     payload body request.UserSavePassword true "Required payload"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /users/save-password [post]
func (_i *usersController) SavePassword(c *fiber.Ctx) error {
	req := new(request.UserSavePassword)
	if err := utilVal.ParseAndValidate(c, req); err != nil {
		return err
	}

	authToken := c.Get("Authorization")

	err := _i.usersService.SavePassword(*req, authToken)
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"Users password successfully update"},
	})
}

// ResetPassword Users
// @Summary      ResetPassword Users
// @Description  API for ResetPassword Users
// @Tags         Users
// @Security     Bearer
// @Param        X-Csrf-Token header string true "Insert the X-Csrf-Token"
// @Param 	     payload body request.UserResetPassword true "Required payload"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /users/reset-password [post]
func (_i *usersController) ResetPassword(c *fiber.Ctx) error {
	req := new(request.UserResetPassword)
	if err := utilVal.ParseAndValidate(c, req); err != nil {
		return err
	}

	err := _i.usersService.ResetPassword(*req)
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"Users password successfully reset"},
	})
}

// ForgotPassword Users
// @Summary      ForgotPassword Users
// @Description  API for ForgotPassword Users
// @Tags         Users
// @Security     Bearer
// @Param        X-Csrf-Token header string true "Insert the X-Csrf-Token"
// @Param 	     payload body request.UserForgotPassword true "Required payload"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /users/forgot-password [post]
func (_i *usersController) ForgotPassword(c *fiber.Ctx) error {
	req := new(request.UserForgotPassword)
	if err := utilVal.ParseAndValidate(c, req); err != nil {
		return err
	}

	err := _i.usersService.ForgotPassword(*req)
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"Users forgot password has sent"},
	})
}

// OtpRequest Users
// @Summary      OtpRequest Users
// @Description  API for OtpRequest Users
// @Tags         Users
// @Security     Bearer
// @Param        X-Csrf-Token header string true "Insert the X-Csrf-Token"
// @Param 	     payload body request.UserOtpRequest true "Required payload"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /users/otp-request [post]
func (_i *usersController) OtpRequest(c *fiber.Ctx) error {
	req := new(request.UserOtpRequest)
	if err := utilVal.ParseAndValidate(c, req); err != nil {
		return err
	}

	err := _i.usersService.OtpRequest(*req)
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"Otp has sent"},
	})
}

// OtpValidation Users
// @Summary      OtpValidation Users
// @Description  API for OtpValidation Users
// @Tags         Users
// @Security     Bearer
// @Param        X-Csrf-Token header string true "Insert the X-Csrf-Token"
// @Param 	     payload body request.UserOtpValidation true "Required payload"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /users/otp-validation [post]
func (_i *usersController) OtpValidation(c *fiber.Ctx) error {
	req := new(request.UserOtpValidation)
	if err := utilVal.ParseAndValidate(c, req); err != nil {
		return err
	}

	err := _i.usersService.OtpValidation(*req)
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{"OTP is valid"},
	})
}

// EmailValidation Users
// @Summary      EmailValidation Users
// @Description  API for Email Validation Users
// @Tags         Users
// @Security     Bearer
// @Param        X-Csrf-Token header string true "Insert the X-Csrf-Token"
// @Param 	     payload body request.UserEmailValidationRequest true "Required payload"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /users/email-validation [post]
func (_i *usersController) EmailValidation(c *fiber.Ctx) error {
	req := new(request.UserEmailValidationRequest)
	if err := utilVal.ParseAndValidate(c, req); err != nil {
		return err
	}

	messageResponse, err := _i.usersService.EmailValidationPreLogin(*req)
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{messageResponse},
	})
}

// SetupEmail Users
// @Summary      SetupEmail Users
// @Description  API for Setup Email Users
// @Tags         Users
// @Security     Bearer
// @Param        X-Csrf-Token header string true "Insert the X-Csrf-Token"
// @Param 	     payload body request.UserEmailValidationRequest true "Required payload"
// @Success      200  {object}  response.Response
// @Failure      400  {object}  response.BadRequestError
// @Failure      401  {object}  response.UnauthorizedError
// @Failure      500  {object}  response.InternalServerError
// @Router       /users/setup-email [post]
func (_i *usersController) SetupEmail(c *fiber.Ctx) error {
	req := new(request.UserEmailValidationRequest)
	if err := utilVal.ParseAndValidate(c, req); err != nil {
		return err
	}

	messageResponse, err := _i.usersService.SetupEmail(*req)
	if err != nil {
		return err
	}

	return utilRes.Resp(c, utilRes.Response{
		Success:  true,
		Messages: utilRes.Messages{messageResponse},
	})
}
