package request

import (
	"encoding/json"
	"jaecoo-be/app/database/entity"
	"jaecoo-be/utils/paginator"
)

type ProductsQueryRequest struct {
	Title      *string               `json:"title"`
	Variant    *string               `json:"variant"`
	Pagination *paginator.Pagination `json:"pagination"`
}

type ProductsQueryRequestContext struct {
	Title   string `json:"title"`
	Variant string `json:"variant"`
}

func (req ProductsQueryRequestContext) ToParamRequest() ProductsQueryRequest {
	var request ProductsQueryRequest

	if title := req.Title; title != "" {
		request.Title = &title
	}
	if variant := req.Variant; variant != "" {
		request.Variant = &variant
	}

	return request
}

type ProductsCreateRequest struct {
	Title         string   `json:"title" validate:"required"`
	Variant       *string  `json:"variant"`
	Price         *string  `json:"price"`
	ThumbnailPath *string  `json:"thumbnail_path"`
	Colors        []string `json:"colors"`
}

func (req ProductsCreateRequest) ToEntity() *entity.Products {
	colorsJSON, _ := json.Marshal(req.Colors)
	colorsStr := string(colorsJSON)
	if colorsStr == "null" {
		colorsStr = ""
	}

	return &entity.Products{
		Title:         req.Title,
		Variant:       req.Variant,
		Price:         req.Price,
		ThumbnailPath: req.ThumbnailPath,
		Colors:        &colorsStr,
	}
}

type ProductsUpdateRequest struct {
	Title         *string  `json:"title"`
	Variant       *string  `json:"variant"`
	Price         *string  `json:"price"`
	ThumbnailPath *string  `json:"thumbnail_path"`
	Colors        []string `json:"colors"`
	IsActive      *bool    `json:"is_active"`
}

func (req ProductsUpdateRequest) ToEntity() *entity.Products {
	colorsJSON, _ := json.Marshal(req.Colors)
	colorsStr := string(colorsJSON)
	if colorsStr == "null" {
		colorsStr = ""
	}

	return &entity.Products{
		Title:         getStringValue(req.Title),
		Variant:       req.Variant,
		Price:         req.Price,
		ThumbnailPath: req.ThumbnailPath,
		Colors:        &colorsStr,
		IsActive:      req.IsActive,
	}
}

func getStringValue(s *string) string {
	if s == nil {
		return ""
	}
	return *s
}
