package repository

import (
	"context"
	"testing"

	"github.com/glebarez/sqlite"
	entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
	"gorm.io/gorm"
)

func TestGetByKandangIDAndLocationIDReturnsLocationMatchedWarehouse(t *testing.T) {
	db := setupWarehouseRepositoryTestDB(t)
	repo := NewWarehouseRepository(db)

	warehouse, err := repo.GetByKandangIDAndLocationID(context.Background(), 5, 13)
	if err != nil {
		t.Fatalf("expected location-matched warehouse, got error: %v", err)
	}
	if warehouse.Id != 33 {
		t.Fatalf("expected warehouse 33, got %d", warehouse.Id)
	}
}

func TestGetByKandangIDKeepsLegacyFirstWarehouseBehavior(t *testing.T) {
	db := setupWarehouseRepositoryTestDB(t)
	repo := NewWarehouseRepository(db)

	warehouse, err := repo.GetByKandangID(context.Background(), 5)
	if err != nil {
		t.Fatalf("expected warehouse, got error: %v", err)
	}
	if warehouse.Id != 17 {
		t.Fatalf("expected legacy first warehouse 17, got %d", warehouse.Id)
	}
}

func setupWarehouseRepositoryTestDB(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)
	}

	if err := db.AutoMigrate(&entity.Warehouse{}); err != nil {
		t.Fatalf("failed migrating warehouses: %v", err)
	}

	warehouses := []entity.Warehouse{
		{Id: 17, Name: "Cijangkar 1", Type: "KANDANG", AreaId: 1, LocationId: uintPtr(1), KandangId: uintPtr(5), CreatedBy: 1},
		{Id: 33, Name: "Gudang Cijangkar 1", Type: "KANDANG", AreaId: 1, LocationId: uintPtr(13), KandangId: uintPtr(5), CreatedBy: 1},
	}
	if err := db.Create(&warehouses).Error; err != nil {
		t.Fatalf("failed seeding warehouses: %v", err)
	}

	return db
}

func uintPtr(v uint) *uint {
	return &v
}
