package services

import (
	"github.com/treytartt/honeydue-api/internal/dto/responses"
	"github.com/treytartt/honeydue-api/internal/repositories"
)

// TaskTemplateService handles business logic for task templates
type TaskTemplateService struct {
	templateRepo *repositories.TaskTemplateRepository
}

// NewTaskTemplateService creates a new task template service
func NewTaskTemplateService(templateRepo *repositories.TaskTemplateRepository) *TaskTemplateService {
	return &TaskTemplateService{
		templateRepo: templateRepo,
	}
}

// GetAll returns all active task templates
func (s *TaskTemplateService) GetAll() ([]responses.TaskTemplateResponse, error) {
	templates, err := s.templateRepo.GetAll()
	if err != nil {
		return nil, err
	}
	return responses.NewTaskTemplateListResponse(templates), nil
}

// GetGrouped returns all templates grouped by category
func (s *TaskTemplateService) GetGrouped() (responses.TaskTemplatesGroupedResponse, error) {
	templates, err := s.templateRepo.GetAll()
	if err != nil {
		return responses.TaskTemplatesGroupedResponse{}, err
	}
	return responses.NewTaskTemplatesGroupedResponse(templates), nil
}

// Search searches templates by query string
func (s *TaskTemplateService) Search(query string) ([]responses.TaskTemplateResponse, error) {
	templates, err := s.templateRepo.Search(query)
	if err != nil {
		return nil, err
	}
	return responses.NewTaskTemplateListResponse(templates), nil
}

// GetByCategory returns templates for a specific category
func (s *TaskTemplateService) GetByCategory(categoryID uint) ([]responses.TaskTemplateResponse, error) {
	templates, err := s.templateRepo.GetByCategory(categoryID)
	if err != nil {
		return nil, err
	}
	return responses.NewTaskTemplateListResponse(templates), nil
}

// GetByID returns a single template by ID
func (s *TaskTemplateService) GetByID(id uint) (*responses.TaskTemplateResponse, error) {
	template, err := s.templateRepo.GetByID(id)
	if err != nil {
		return nil, err
	}
	resp := responses.NewTaskTemplateResponse(template)
	return &resp, nil
}

// Count returns the total count of active templates
func (s *TaskTemplateService) Count() (int64, error) {
	return s.templateRepo.Count()
}
