package purchasing

import (
	"context"
	"errors"
	"testing"
)

// The print-once ledger (000150): "PO dicetak untuk approve atasan, status
// print hanya bisa sekali". The service stamp is the gate the report proxy
// calls at render time.
func TestStampPrint_FirstPrintSucceedsAndCounts(t *testing.T) {
	s := svc()
	fs := s.store.(*fakeStore)
	fs.orders[1] = &PurchaseOrder{ID: 1, Status: "approved"}

	out, err := s.StampPrint(context.Background(), 1, 42, false)
	if err != nil {
		t.Fatalf("first print err = %v, want nil", err)
	}
	if out.PrintCount != 1 {
		t.Errorf("print_count = %d, want 1", out.PrintCount)
	}
	if out.PrintedAt == nil {
		t.Error("printed_at nil after the first print")
	}
}

func TestStampPrint_SecondPrintRefusedWithoutBypass(t *testing.T) {
	s := svc()
	fs := s.store.(*fakeStore)
	fs.orders[1] = &PurchaseOrder{ID: 1, Status: "approved", PrintCount: 1}

	if _, err := s.StampPrint(context.Background(), 1, 42, false); !errors.Is(err, ErrAlreadyPrinted) {
		t.Fatalf("second print err = %v, want ErrAlreadyPrinted", err)
	}
	// The ledger must not have moved.
	if got := fs.orders[1].PrintCount; got != 1 {
		t.Errorf("print_count = %d after a refused print, want 1", got)
	}
}

func TestStampPrint_ReprintAllowedWithBypass(t *testing.T) {
	s := svc()
	fs := s.store.(*fakeStore)
	fs.orders[1] = &PurchaseOrder{ID: 1, Status: "approved", PrintCount: 1}

	out, err := s.StampPrint(context.Background(), 1, 42, true)
	if err != nil {
		t.Fatalf("bypassed reprint err = %v, want nil", err)
	}
	if out.PrintCount != 2 {
		t.Errorf("print_count = %d, want 2 (reprint recorded, never hidden)", out.PrintCount)
	}
}

func TestStampPrint_MissingOrderIsNotFound(t *testing.T) {
	s := svc()
	// execrows==0 on an unknown id maps to ErrAlreadyPrinted at the service —
	// indistinguishable from "already printed" and equally refusable; the
	// important part is that no order data comes back.
	if _, err := s.StampPrint(context.Background(), 99, 42, false); !errors.Is(err, ErrAlreadyPrinted) {
		t.Fatalf("missing-order stamp err = %v, want ErrAlreadyPrinted", err)
	}
}
