package warehouses

import (
	"context"
	"testing"
	"time"

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

type fakeStore struct {
	items  map[int64]*db.Warehouse
	nextID int64
}

func newFakeStore() *fakeStore {
	return &fakeStore{items: map[int64]*db.Warehouse{}, nextID: 1}
}

func (f *fakeStore) List(context.Context, int, int, string) ([]db.Warehouse, int, error) {
	return nil, 0, nil
}
func (f *fakeStore) Options(context.Context) ([]Option, error) {
	return []Option{{ID: 1, Code: "GDG-001", Name: "Gudang Pusat"}}, nil
}
func (f *fakeStore) ByID(_ context.Context, id int64) (*db.Warehouse, error) {
	if w, ok := f.items[id]; ok {
		return w, nil
	}
	return nil, ErrNotFound
}
func (f *fakeStore) Create(_ context.Context, w *db.Warehouse) error {
	w.ID = f.nextID
	f.nextID++
	f.items[w.ID] = w
	return nil
}
func (f *fakeStore) Update(_ context.Context, w *db.Warehouse) error {
	if _, ok := f.items[w.ID]; !ok {
		return ErrNotFound
	}
	f.items[w.ID] = w
	return nil
}
func (f *fakeStore) Delete(context.Context, int64) error { return nil }

type fakeSeq struct{ n int64 }

func (f *fakeSeq) Sequence(context.Context, string, time.Time, any) (int64, error) {
	f.n++
	return f.n, nil
}

func TestCreate_Code(t *testing.T) {
	svc := NewService(newFakeStore(), &fakeSeq{}, time.UTC)
	w, err := svc.Create(context.Background(), Input{Name: "Gudang Pusat"})
	if err != nil {
		t.Fatal(err)
	}
	if w.Code != "GDG-001" {
		t.Errorf("code = %q, want GDG-001", w.Code)
	}
}

func TestCreate_SequentialCodes(t *testing.T) {
	svc := NewService(newFakeStore(), &fakeSeq{}, time.UTC)
	seq := []struct{ want string }{
		{"GDG-001"}, {"GDG-002"}, {"GDG-003"},
	}
	for i, tc := range seq {
		w, err := svc.Create(context.Background(), Input{Name: "G"})
		if err != nil {
			t.Fatal(err)
		}
		if i < len(seq) && w.Code != tc.want {
			t.Errorf("code = %q, want %q", w.Code, tc.want)
		}
	}
}

func TestCreate_EmptyName(t *testing.T) {
	svc := NewService(newFakeStore(), &fakeSeq{}, time.UTC)
	if _, err := svc.Create(context.Background(), Input{}); err == nil {
		t.Fatal("want error for empty name")
	}
}

func TestUpdate_UnknownID(t *testing.T) {
	svc := NewService(newFakeStore(), &fakeSeq{}, time.UTC)
	if _, err := svc.Update(context.Background(), 42, Input{Name: "X"}); err != ErrNotFound {
		t.Fatalf("got %v, want ErrNotFound", err)
	}
}

func TestOptions_SlimList(t *testing.T) {
	svc := NewService(newFakeStore(), &fakeSeq{}, time.UTC)
	opts, err := svc.Options(context.Background())
	if err != nil {
		t.Fatal(err)
	}
	if len(opts) != 1 {
		t.Fatalf("len = %d, want 1", len(opts))
	}
	if opts[0].ID != 1 || opts[0].Code != "GDG-001" || opts[0].Name != "Gudang Pusat" {
		t.Errorf("option = %+v, want {1 GDG-001 Gudang Pusat}", opts[0])
	}
}
