package service

import (
	"context"
	"testing"
	"time"

	"github.com/glebarez/sqlite"
	repository "gitlab.com/mbugroup/lti-api.git/internal/modules/closings/repositories"
	"gorm.io/gorm"
)

func TestGetSapronakDateRange_ProjectWithoutChickin_DoesNotError(t *testing.T) {
	db := setupClosingServiceTestDB(t)
	repo := repository.NewClosingRepository(db)
	svc := closingService{Repository: repo}

	createdAt := time.Date(2026, 4, 15, 7, 0, 0, 0, time.UTC)
	if err := db.Exec(`INSERT INTO project_flock_kandangs (id, project_flock_id, created_at, closed_at) VALUES (66, 47, ?, NULL)`, createdAt).Error; err != nil {
		t.Fatalf("failed seeding project_flock_kandangs: %v", err)
	}

	start, end, err := svc.getSapronakDateRange(context.Background(), 47, nil)
	if err != nil {
		t.Fatalf("expected no error, got %v", err)
	}
	if start == nil {
		t.Fatalf("expected non-nil start date")
	}
	expected := dateOnlyUTC(createdAt)
	if !start.Equal(expected) {
		t.Fatalf("expected start %s, got %s", expected.Format(time.RFC3339), start.Format(time.RFC3339))
	}
	if end != nil {
		t.Fatalf("expected nil end date for open kandang, got %v", end)
	}
}

func TestGetSapronakDateRange_KandangWithoutChickin_DoesNotError(t *testing.T) {
	db := setupClosingServiceTestDB(t)
	repo := repository.NewClosingRepository(db)
	svc := closingService{Repository: repo}

	createdAt := time.Date(2026, 4, 15, 7, 0, 0, 0, time.UTC)
	if err := db.Exec(`INSERT INTO project_flock_kandangs (id, project_flock_id, created_at, closed_at) VALUES (66, 47, ?, NULL)`, createdAt).Error; err != nil {
		t.Fatalf("failed seeding project_flock_kandangs: %v", err)
	}

	pfkID := uint(66)
	start, end, err := svc.getSapronakDateRange(context.Background(), 47, &pfkID)
	if err != nil {
		t.Fatalf("expected no error, got %v", err)
	}
	if start == nil {
		t.Fatalf("expected non-nil start date")
	}
	expected := dateOnlyUTC(createdAt)
	if !start.Equal(expected) {
		t.Fatalf("expected start %s, got %s", expected.Format(time.RFC3339), start.Format(time.RFC3339))
	}
	if end != nil {
		t.Fatalf("expected nil end date for open kandang, got %v", end)
	}
}

func setupClosingServiceTestDB(t *testing.T) *gorm.DB {
	t.Helper()

	db, err := gorm.Open(sqlite.Open("file:"+t.Name()+"?mode=memory&cache=private"), &gorm.Config{})
	if err != nil {
		t.Fatalf("failed opening sqlite db: %v", err)
	}

	stmts := []string{
		`CREATE TABLE project_flock_kandangs (
			id INTEGER PRIMARY KEY,
			project_flock_id INTEGER NOT NULL,
			created_at TIMESTAMP NOT NULL,
			closed_at TIMESTAMP NULL
		)`,
		`CREATE TABLE project_chickins (
			id INTEGER PRIMARY KEY,
			project_flock_kandang_id INTEGER NOT NULL,
			chick_in_date TIMESTAMP NULL
		)`,
	}
	for _, stmt := range stmts {
		if err := db.Exec(stmt).Error; err != nil {
			t.Fatalf("failed preparing schema: %v", err)
		}
	}

	return db
}
