package service

import (
	"testing"
	"time"

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

func mustDate(t *testing.T, value string) time.Time {
	t.Helper()
	parsed, err := time.Parse("2006-01-02", value)
	if err != nil {
		t.Fatalf("failed parsing date %s: %v", value, err)
	}
	return parsed
}

func TestTransferRecordingWindow(t *testing.T) {
	t.Run("early transfer keeps transition until economic cutoff", func(t *testing.T) {
		physical := mustDate(t, "2026-04-08")
		cutoff := mustDate(t, "2026-05-13")
		transfer := &entity.LayingTransfer{
			TransferDate:       physical,
			EconomicCutoffDate: &cutoff,
		}

		gotPhysical, gotCutoff := transferRecordingWindow(transfer)
		if gotPhysical.Format("2006-01-02") != "2026-04-08" {
			t.Fatalf("unexpected physical date: %s", gotPhysical.Format("2006-01-02"))
		}
		if gotCutoff.Format("2006-01-02") != "2026-05-13" {
			t.Fatalf("unexpected cutoff date: %s", gotCutoff.Format("2006-01-02"))
		}
	})

	t.Run("standard transfer has no transition window", func(t *testing.T) {
		physical := mustDate(t, "2026-05-13")
		cutoff := mustDate(t, "2026-05-13")
		transfer := &entity.LayingTransfer{
			TransferDate:       physical,
			EconomicCutoffDate: &cutoff,
		}

		gotPhysical, gotCutoff := transferRecordingWindow(transfer)
		if gotPhysical.Format("2006-01-02") != "2026-05-13" {
			t.Fatalf("unexpected physical date: %s", gotPhysical.Format("2006-01-02"))
		}
		if gotCutoff.Format("2006-01-02") != "2026-05-13" {
			t.Fatalf("unexpected cutoff date: %s", gotCutoff.Format("2006-01-02"))
		}
	})

	t.Run("late transfer clamps economic cutoff to physical move", func(t *testing.T) {
		physical := mustDate(t, "2026-06-03")
		cutoff := mustDate(t, "2026-05-13")
		transfer := &entity.LayingTransfer{
			TransferDate:       physical,
			EconomicCutoffDate: &cutoff,
		}

		gotPhysical, gotCutoff := transferRecordingWindow(transfer)
		if gotPhysical.Format("2006-01-02") != "2026-06-03" {
			t.Fatalf("unexpected physical date: %s", gotPhysical.Format("2006-01-02"))
		}
		if gotCutoff.Format("2006-01-02") != "2026-06-03" {
			t.Fatalf("unexpected cutoff date: %s", gotCutoff.Format("2006-01-02"))
		}
	})

	t.Run("legacy data falls back to effective move date", func(t *testing.T) {
		physical := mustDate(t, "2026-04-08")
		legacyEffective := mustDate(t, "2026-05-13")
		transfer := &entity.LayingTransfer{
			TransferDate:      physical,
			EffectiveMoveDate: &legacyEffective,
		}

		gotPhysical, gotCutoff := transferRecordingWindow(transfer)
		if gotPhysical.Format("2006-01-02") != "2026-04-08" {
			t.Fatalf("unexpected physical date: %s", gotPhysical.Format("2006-01-02"))
		}
		if gotCutoff.Format("2006-01-02") != "2026-05-13" {
			t.Fatalf("unexpected cutoff date: %s", gotCutoff.Format("2006-01-02"))
		}
	})
}
