package services

import (
	"errors"
	"time"

	"gauth-central/internal/database"
	"gauth-central/internal/models"

	"github.com/google/uuid"
	"gorm.io/gorm"
)

type PostCategoryViewService struct{}

func NewPostCategoryViewService() *PostCategoryViewService {
	return &PostCategoryViewService{}
}

// TrackView records a category view once per day per IP.
func (s *PostCategoryViewService) TrackView(categoryID string, ipAddress string, userAgent string) (*models.PostCategoryView, error) {
	categoryUUID, err := uuid.Parse(categoryID)
	if err != nil {
		return nil, errors.New("invalid category_id")
	}

	startOfDay := time.Now().UTC().Truncate(24 * time.Hour)
	endOfDay := startOfDay.Add(24 * time.Hour)

	var existing models.PostCategoryView
	err = database.DB.Where(
		"category_id = ? AND ip_address = ? AND created_at >= ? AND created_at < ?",
		categoryUUID,
		ipAddress,
		startOfDay,
		endOfDay,
	).First(&existing).Error
	if err == nil {
		return &existing, nil
	}
	if !errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, err
	}

	view := models.PostCategoryView{
		CategoryID: categoryUUID,
		IPAddress:  ipAddress,
		UserAgent:  userAgent,
	}

	if err := database.DB.Create(&view).Error; err != nil {
		return nil, err
	}

	return &view, nil
}

// GetViewsByCategory returns all views for a category.
func (s *PostCategoryViewService) GetViewsByCategory(categoryID string) ([]models.PostCategoryView, error) {
	var views []models.PostCategoryView
	if err := database.DB.Where("category_id = ?", categoryID).Order("created_at desc").Find(&views).Error; err != nil {
		return nil, err
	}
	return views, nil
}
