package service

import (
	"testing"
	"time"

	"gitlab.com/mbugroup/lti-api.git/internal/config"
	entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
	"gitlab.com/mbugroup/lti-api.git/internal/utils"
)

func TestComputeUniformityWeekForPFK(t *testing.T) {
	originalWeekStart := config.TransferToLayingGrowingMaxWeek
	config.TransferToLayingGrowingMaxWeek = 19
	t.Cleanup(func() {
		config.TransferToLayingGrowingMaxWeek = originalWeekStart
	})

	svc := &uniformityService{}
	baseDate := time.Date(2026, time.January, 1, 9, 30, 0, 0, time.UTC)

	t.Run("growing starts from week one", func(t *testing.T) {
		pfk := &entity.ProjectFlockKandang{
			Id: 1,
			ProjectFlock: entity.ProjectFlock{
				Category: string(utils.ProjectFlockCategoryGrowing),
			},
			Chickins: []entity.ProjectChickin{
				{ChickInDate: baseDate},
			},
		}

		week, err := svc.computeUniformityWeekForPFK(pfk, baseDate)
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		if week != 1 {
			t.Fatalf("expected week 1, got %d", week)
		}
	})

	t.Run("laying uses configured week base and earliest chick in", func(t *testing.T) {
		pfk := &entity.ProjectFlockKandang{
			Id: 2,
			ProjectFlock: entity.ProjectFlock{
				Category: string(utils.ProjectFlockCategoryLaying),
			},
			Chickins: []entity.ProjectChickin{
				{ChickInDate: baseDate.AddDate(0, 0, 4)},
				{ChickInDate: baseDate},
			},
		}

		week, err := svc.computeUniformityWeekForPFK(pfk, baseDate.AddDate(0, 0, 7))
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		if week != 20 {
			t.Fatalf("expected week 20, got %d", week)
		}
	})

	t.Run("rejects date before chick in", func(t *testing.T) {
		pfk := &entity.ProjectFlockKandang{
			Id: 3,
			ProjectFlock: entity.ProjectFlock{
				Category: string(utils.ProjectFlockCategoryLaying),
			},
			Chickins: []entity.ProjectChickin{
				{ChickInDate: baseDate},
			},
		}

		if _, err := svc.computeUniformityWeekForPFK(pfk, baseDate.AddDate(0, 0, -1)); err == nil {
			t.Fatal("expected error for date before chick in")
		}
	})
}
