package request

import (
	"strconv"
	"time"
	"web-qudo-be/app/database/entity"
	userRoleAccessReq "web-qudo-be/app/module/user_role_accesses/request"
	"web-qudo-be/utils/paginator"
)

type UserRolesGeneric interface {
	ToEntity()
}

type UserRolesQueryRequest struct {
	Name        *string               `json:"name"`
	Description *string               `json:"description"`
	Code        *string               `json:"code"`
	UserLevelId *int                  `json:"userLevelId"`
	StatusId    *int                  `json:"statusId"`
	Pagination  *paginator.Pagination `json:"pagination"`
}

type UserRolesCreateRequest struct {
	Name           string                                            `json:"name" validate:"required"`
	Description    string                                            `json:"description" validate:"required"`
	Code           string                                            `json:"code" validate:"required"`
	UserLevelIds   []uint                                            `json:"userLevelIds" validate:"required"`
	UserRoleAccess []userRoleAccessReq.UserRoleAccessesCreateRequest `json:"userRoleAccess" validate:"required"`
	StatusId       int                                               `json:"statusId" validate:"required"`
}

func (req UserRolesCreateRequest) ToEntity() *entity.UserRoles {
	return &entity.UserRoles{
		Name:        req.Name,
		Description: req.Description,
		Code:        req.Code,
		StatusId:    req.StatusId,
	}
}

type UserRolesUpdateRequest struct {
	Name         string `json:"name" validate:"required"`
	Description  string `json:"description" validate:"required"`
	Code         string `json:"code" validate:"required"`
	LevelNumber  int    `json:"level_number" validate:"required"`
	UserLevelIds []uint `json:"userLevelIds" validate:"required"`
	StatusId     int    `json:"status_id" validate:"required"`
}

func (req UserRolesUpdateRequest) ToEntity() *entity.UserRoles {
	return &entity.UserRoles{
		Name:        req.Name,
		Description: req.Description,
		Code:        req.Code,
		StatusId:    req.StatusId,
		UpdatedAt:   time.Now(),
	}
}

type UserRolesQueryRequestContext struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Code        string `json:"code"`
	UserLevelId string `json:"userLevelId"`
	StatusId    string `json:"statusId"`
}

func (req UserRolesQueryRequestContext) ToParamRequest() UserRolesQueryRequest {
	var request UserRolesQueryRequest

	if name := req.Name; name != "" {
		request.Name = &name
	}
	if code := req.Code; code != "" {
		request.Code = &code
	}
	if userLevelIdStr := req.UserLevelId; userLevelIdStr != "" {
		userLevelId, err := strconv.Atoi(userLevelIdStr)
		if err == nil {
			request.UserLevelId = &userLevelId
		}
	}
	if statusIdStr := req.StatusId; statusIdStr != "" {
		statusId, err := strconv.Atoi(statusIdStr)
		if err == nil {
			request.StatusId = &statusId
		}
	}

	return request
}
