package calc

import (
	"math"

	"git.dumerain.org/alban/paycheck/internal/models"
)

/*
Le moteur de calcul est volontairement isolé du reste.
Ça facilite :
- les tests unitaires
- l'évolution des règles
- le support de nouveaux codes
*/

func round2(v float64) float64 {
	return math.Round(v*100) / 100
}

func Compute(req models.CalculateRequest, profile models.Profile, rules models.GlobalRules) models.CalculateResponse {
	// Chaque ligne = taux * quantité, arrondi au centime.
	// Libellés volontairement "fiche de paie" (courts) pour que UI + PDF collent.
	lines := []models.Line{
		{
			Code:     "456",
			Label:    "Interv.astreinte Jour",
			Rate:     profile.T456,
			Quantity: req.Q456,
			Unit:     "h",
			Amount:   round2(profile.T456 * req.Q456),
		},
		{
			Code:     "458",
			Label:    "Interv.astreinte Dim & JF",
			Rate:     profile.T458,
			Quantity: req.Q458,
			Unit:     "h",
			Amount:   round2(profile.T458 * req.Q458),
		},
		{
			Code:     "459",
			Label:    "Interv.astreinte Nuit",
			Rate:     profile.T459,
			Quantity: req.Q459,
			Unit:     "h",
			Amount:   round2(profile.T459 * req.Q459),
		},
		{
			Code:     "471",
			Label:    "Astreinte",
			Rate:     profile.T471,
			Quantity: req.Q471,
			Unit:     "h",
			Amount:   round2(profile.T471 * req.Q471),
		},
		{
			Code:     "480",
			Label:    "Ind. Forfait. Dim & JF",
			Rate:     rules.ForfaitDimFerie,
			Quantity: float64(req.NbDimFerie),
			Unit:     "j",
			Amount:   round2(rules.ForfaitDimFerie * float64(req.NbDimFerie)),
		},
	}

	// Total = somme des montants déjà arrondis (comportement typique paie).
	total := 0.0
	for _, l := range lines {
		total += l.Amount
	}

	return models.CalculateResponse{Lines: lines, Total: round2(total)}
}
