package request

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

type ResearchJournalsQueryRequest struct {
	UserID         uint                  `json:"userId" validate:"required"`
	JournalTitle  *string               `json:"journalTitle"`
	Publisher     *string               `json:"publisher"`
	PublishedYear *int                  `json:"publishedYear"`
	Pagination    *paginator.Pagination `json:"pagination"`
}

type ResearchJournalsCreateRequest struct {
	JournalTitle  string     `json:"journalTitle" validate:"required,min=2,max=500"`
	Publisher     string     `json:"publisher" validate:"required,min=2,max=255"`
	JournalURL    string     `json:"journalUrl" validate:"required,url"`
	PublishedDate *time.Time `json:"publishedDate"`
}

func (req ResearchJournalsCreateRequest) ToEntity() *entity.ResearchJournals {
	return &entity.ResearchJournals{
		JournalTitle:  req.JournalTitle,
		Publisher:     req.Publisher,
		JournalURL:    req.JournalURL,
		PublishedDate: req.PublishedDate,
	}
}

type ResearchJournalsUpdateRequest struct {
	JournalTitle  string     `json:"journalTitle" validate:"required,min=2,max=500"`
	Publisher     string     `json:"publisher" validate:"required,min=2,max=255"`
	JournalURL    string     `json:"journalUrl" validate:"required,url"`
	PublishedDate *time.Time `json:"publishedDate"`
}

func (req ResearchJournalsUpdateRequest) ToEntity() *entity.ResearchJournals {
	return &entity.ResearchJournals{
		JournalTitle:  req.JournalTitle,
		Publisher:     req.Publisher,
		JournalURL:    req.JournalURL,
		PublishedDate: req.PublishedDate,
	}
}

type ResearchJournalsQueryRequestContext struct {
	UserID         string `json:"userId"`
	JournalTitle  string `json:"journalTitle"`
	Publisher     string `json:"publisher"`
	PublishedYear string `json:"publishedYear"`
}

func (req ResearchJournalsQueryRequestContext) ToParamRequest() ResearchJournalsQueryRequest {
	var request ResearchJournalsQueryRequest

		if userId := req.UserID; userId != "" {
		userIdUint, err := strconv.ParseUint(userId, 10, 0)
		if err == nil {
			request.UserID = uint(userIdUint)
		}
	}

	if journalTitle := req.JournalTitle; journalTitle != "" {
		request.JournalTitle = &journalTitle
	}
	if publisher := req.Publisher; publisher != "" {
		request.Publisher = &publisher
	}
	if publishedYearStr := req.PublishedYear; publishedYearStr != "" {
		// Extract year from publishedYearStr if it's a date string
		if publishedYearStr != "" {
			// For now, we'll handle this in the repository layer
			// This could be enhanced to parse date strings
		}
	}

	return request
}
