package request

import (
	"campaign-pool-be/app/database/entity"
	"campaign-pool-be/utils/paginator"
	"strconv"
	"time"
)

type EbookRatingsGeneric interface {
	ToEntity()
}

type EbookRatingsQueryRequest struct {
	EbookId    *uint                 `json:"ebookId"`
	UserId     *uint                 `json:"userId"`
	Rating     *int                  `json:"rating"`
	IsVerified *bool                 `json:"isVerified"`
	StatusId   *int                  `json:"statusId"`
	Pagination *paginator.Pagination `json:"pagination"`
}

type EbookRatingsCreateRequest struct {
	EbookId     uint    `json:"ebookId" validate:"required"`
	PurchaseId  uint    `json:"purchaseId" validate:"required"`
	Rating      int     `json:"rating" validate:"required,min=1,max=5"`
	Review      *string `json:"review"`
	IsAnonymous *bool   `json:"isAnonymous"`
}

func (req EbookRatingsCreateRequest) ToEntity() *entity.EbookRatings {
	return &entity.EbookRatings{
		EbookId:     req.EbookId,
		PurchaseId:  req.PurchaseId,
		Rating:      req.Rating,
		Review:      req.Review,
		IsAnonymous: req.IsAnonymous,
		IsVerified:  boolPtr(true),
		StatusId:    intPtr(1),
		IsActive:    boolPtr(true),
	}
}

type EbookRatingsUpdateRequest struct {
	Rating      int     `json:"rating" validate:"required,min=1,max=5"`
	Review      *string `json:"review"`
	IsAnonymous *bool   `json:"isAnonymous"`
}

func (req EbookRatingsUpdateRequest) ToEntity() *entity.EbookRatings {
	return &entity.EbookRatings{
		Rating:      req.Rating,
		Review:      req.Review,
		IsAnonymous: req.IsAnonymous,
		UpdatedAt:   time.Now(),
	}
}

type EbookRatingsQueryRequestContext struct {
	EbookId    string `json:"ebookId"`
	UserId     string `json:"userId"`
	Rating     string `json:"rating"`
	IsVerified string `json:"isVerified"`
	StatusId   string `json:"statusId"`
}

func (req EbookRatingsQueryRequestContext) ToParamRequest() EbookRatingsQueryRequest {
	var request EbookRatingsQueryRequest

	if ebookIdStr := req.EbookId; ebookIdStr != "" {
		ebookId, err := strconv.Atoi(ebookIdStr)
		if err == nil {
			ebookIdUint := uint(ebookId)
			request.EbookId = &ebookIdUint
		}
	}
	if userIdStr := req.UserId; userIdStr != "" {
		userId, err := strconv.Atoi(userIdStr)
		if err == nil {
			userIdUint := uint(userId)
			request.UserId = &userIdUint
		}
	}
	if ratingStr := req.Rating; ratingStr != "" {
		rating, err := strconv.Atoi(ratingStr)
		if err == nil {
			request.Rating = &rating
		}
	}
	if isVerifiedStr := req.IsVerified; isVerifiedStr != "" {
		isVerified, err := strconv.ParseBool(isVerifiedStr)
		if err == nil {
			request.IsVerified = &isVerified
		}
	}
	if statusIdStr := req.StatusId; statusIdStr != "" {
		statusId, err := strconv.Atoi(statusIdStr)
		if err == nil {
			request.StatusId = &statusId
		}
	}

	return request
}

// Helper functions
func boolPtr(b bool) *bool {
	return &b
}

func intPtr(i int) *int {
	return &i
}
