package request

import (
	"narasi-ahli-be/app/database/entity"
	"narasi-ahli-be/utils/paginator"
	"strconv"
	"time"
)

type WorkHistoryQueryRequest struct {
	UserID      uint                  `json:"userId" validate:"required"`
	JobTitle    *string               `json:"jobTitle"`
	CompanyName *string               `json:"companyName"`
	IsCurrent   *bool                 `json:"isCurrent"` // filter for current job (EndDate is null)
	Pagination  *paginator.Pagination `json:"pagination"`
}

type WorkHistoryCreateRequest struct {
	JobTitle    string     `json:"jobTitle" validate:"required,min=2,max=255"`
	CompanyName string     `json:"companyName" validate:"required,min=2,max=255"`
	StartDate   time.Time  `json:"startDate" validate:"required"`
	EndDate     *time.Time `json:"endDate"`
}

func (req WorkHistoryCreateRequest) ToEntity(userId uint) *entity.WorkHistory {
	return &entity.WorkHistory{
		UserID:      userId,
		JobTitle:    req.JobTitle,
		CompanyName: req.CompanyName,
		StartDate:   req.StartDate,
		EndDate:     req.EndDate,
	}
}

type WorkHistoryUpdateRequest struct {
	JobTitle    string     `json:"jobTitle" validate:"required,min=2,max=255"`
	CompanyName string     `json:"companyName" validate:"required,min=2,max=255"`
	StartDate   time.Time  `json:"startDate" validate:"required"`
	EndDate     *time.Time `json:"endDate"`
}

func (req WorkHistoryUpdateRequest) ToEntity(userId uint) *entity.WorkHistory {
	return &entity.WorkHistory{
		UserID:      userId,
		JobTitle:    req.JobTitle,
		CompanyName: req.CompanyName,
		StartDate:   req.StartDate,
		EndDate:     req.EndDate,
	}
}

type WorkHistoryQueryRequestContext struct {
	UserID      string `json:"userId"`
	JobTitle    string `json:"jobTitle"`
	CompanyName string `json:"companyName"`
	IsCurrent   string `json:"isCurrent"`
}

func (req WorkHistoryQueryRequestContext) ToParamRequest() WorkHistoryQueryRequest {
	var request WorkHistoryQueryRequest

	if userId := req.UserID; userId != "" {
		userIdUint, err := strconv.ParseUint(userId, 10, 0)
		if err == nil {
			request.UserID = uint(userIdUint)
		}
	}
	if jobTitle := req.JobTitle; jobTitle != "" {
		request.JobTitle = &jobTitle
	}
	if companyName := req.CompanyName; companyName != "" {
		request.CompanyName = &companyName
	}
	if isCurrent := req.IsCurrent; isCurrent != "" {
		if isCurrent == "true" {
			isCurrentBool := true
			request.IsCurrent = &isCurrentBool
		} else if isCurrent == "false" {
			isCurrentBool := false
			request.IsCurrent = &isCurrentBool
		}
	}

	return request
}
