package system

// Warehouse retirement on store delete.
//
// Deleting the last store bound to a warehouse used to leave the warehouse
// active, so checkout pickers (B2B + POS read active-only options) kept
// offering a hub with no store behind it. DeleteStore now retires it: hard
// delete when nothing ever touched it, deactivate when stock or transactional
// history exists (history must stay intact, but hidden from pickers).

import (
	"context"
	"testing"
	"time"

	"github.com/TaruLab/keluargamart-backend/internal/db"
)

func retireFixture() *fakeStore {
	f := newFakeStore()
	f.storeRows = map[int64]db.Store{
		1: {ID: 1, Code: "T1", Name: "Toko 1", WarehouseID: 11},
		2: {ID: 2, Code: "T2", Name: "Toko 2", WarehouseID: 12},
		3: {ID: 3, Code: "T3", Name: "Toko 3", WarehouseID: 13},
	}
	return f
}

func newRetireService(f *fakeStore) *Service {
	return NewService(f, time.UTC)
}

func TestDeleteStore_RemovesUnusedWarehouse(t *testing.T) {
	f := retireFixture()
	s := newRetireService(f)
	// Warehouse 11 has no other store and nothing in it: hard delete.
	f.storesByWh = map[int64]int64{11: 0}
	if err := s.DeleteStore(context.Background(), 1); err != nil {
		t.Fatal(err)
	}
	if len(f.deletedWh) != 1 || f.deletedWh[0] != 11 {
		t.Fatalf("deletedWh = %v, want [11]", f.deletedWh)
	}
	if len(f.deactivated) != 0 {
		t.Fatalf("deactivated = %v, want none", f.deactivated)
	}
}

func TestDeleteStore_DeactivatesUsedWarehouse(t *testing.T) {
	f := retireFixture()
	s := newRetireService(f)
	// Warehouse 12 is empty of siblings but holds stock/history: deactivate,
	// never delete.
	f.storesByWh = map[int64]int64{12: 0}
	f.whUsed = map[int64]bool{12: true}
	if err := s.DeleteStore(context.Background(), 2); err != nil {
		t.Fatal(err)
	}
	if len(f.deactivated) != 1 || f.deactivated[0] != 12 {
		t.Fatalf("deactivated = %v, want [12]", f.deactivated)
	}
	if len(f.deletedWh) != 0 {
		t.Fatalf("deletedWh = %v, want none (history must survive)", f.deletedWh)
	}
}

func TestDeleteStore_KeepsSharedWarehouse(t *testing.T) {
	f := retireFixture()
	s := newRetireService(f)
	// Another store still points at warehouse 13: leave it alone entirely.
	f.storesByWh = map[int64]int64{13: 2}
	f.whUsed = map[int64]bool{13: true}
	if err := s.DeleteStore(context.Background(), 3); err != nil {
		t.Fatal(err)
	}
	if len(f.deactivated) != 0 || len(f.deletedWh) != 0 {
		t.Fatalf("shared warehouse touched: deactivated=%v deleted=%v", f.deactivated, f.deletedWh)
	}
}
