package service

import (
	"context"
	"go-server/internal/repository"
)

type DailyOverviewService struct {
	dailyRepo *repository.DailyOverviewRepository
}

func NewDailyOverviewService(dailyRepo *repository.DailyOverviewRepository) *DailyOverviewService {
	return &DailyOverviewService{
		dailyRepo: dailyRepo,
	}
}

// DailyNutrientSummary represents the complete daily overview
type DailyNutrientSummary struct {
	NutrientTotals      []repository.NutrientTotal             `json:"nutrientTotals"`
	ByCategory          map[string][]repository.NutrientTotal  `json:"byCategory"`
	SupplementBreakdown []repository.SupplementNutrientDetails `json:"supplementBreakdown"`
	Summary             DailySummaryStats                      `json:"summary"`
}

type DailySummaryStats struct {
	TotalNutrients   int `json:"totalNutrients"`
	TotalSupplements int `json:"totalSupplements"`
	CategoriesCount  int `json:"categoriesCount"`
}

// GetDailyOverview returns a comprehensive overview of daily nutrient intake
func (s *DailyOverviewService) GetDailyOverview(ctx context.Context) (*DailyNutrientSummary, error) {
	// Get nutrient totals
	totals, err := s.dailyRepo.GetNutrientTotals(ctx)
	if err != nil {
		return nil, err
	}

	// Get breakdown by category
	byCategory, err := s.dailyRepo.GetNutrientsByCategory(ctx)
	if err != nil {
		return nil, err
	}

	// Get supplement breakdown
	breakdown, err := s.dailyRepo.GetSupplementBreakdown(ctx)
	if err != nil {
		return nil, err
	}

	// Calculate summary stats
	supplementMap := make(map[string]bool)
	for _, item := range breakdown {
		supplementMap[item.SupplementName] = true
	}

	summary := DailySummaryStats{
		TotalNutrients:   len(totals),
		TotalSupplements: len(supplementMap),
		CategoriesCount:  len(byCategory),
	}

	return &DailyNutrientSummary{
		NutrientTotals:      totals,
		ByCategory:          byCategory,
		SupplementBreakdown: breakdown,
		Summary:             summary,
	}, nil
}

// GetNutrientTotals returns just the aggregated totals
func (s *DailyOverviewService) GetNutrientTotals(ctx context.Context) ([]repository.NutrientTotal, error) {
	return s.dailyRepo.GetNutrientTotals(ctx)
}

// GetSupplementBreakdown returns detailed breakdown by supplement
func (s *DailyOverviewService) GetSupplementBreakdown(ctx context.Context) ([]repository.SupplementNutrientDetails, error) {
	return s.dailyRepo.GetSupplementBreakdown(ctx)
}

// ExecuteCustomQuery allows executing custom SQL queries
// This gives you maximum flexibility for complex analytics
func (s *DailyOverviewService) ExecuteCustomQuery(ctx context.Context, query string, args ...interface{}) ([]map[string]interface{}, error) {
	return s.dailyRepo.ExecuteRawQueryWithResult(ctx, query, args...)
}
