package integration

import (
	"context"
	"testing"

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

// Migration 000098 exists specifically to keep the buyer /me dashboard fast.
// These checks run only against a real database (DATABASE_URL): verify the
// indexes are present and the /me aggregate queries return sane numbers.
func TestMeViewsIndexes(t *testing.T) {
	pool := testPool(t) // skips when DATABASE_URL is unset
	tdb := pool
	ctx := context.Background()

	t.Run("indexes exist", func(t *testing.T) {
		for _, name := range []string{
			"idx_sales_orders_customer_type_id",
			"idx_payments_created_id",
			"idx_invoices_customer_id",
		} {
			var n int
			if err := tdb.QueryRow(ctx,
				`SELECT count(*) FROM pg_indexes WHERE indexname = $1`, name).Scan(&n); err != nil {
				t.Fatal(err)
			}
			if n != 1 {
				t.Fatalf("index %s missing after migration 000098", name)
			}
		}
	})

	t.Run("SumCustomerPayments aggregates only invoice payments", func(t *testing.T) {
		q := db.New(tdb)
		row, err := q.SumCustomerPayments(ctx, db.SumCustomerPaymentsParams{CustomerID: 999999})
		if err != nil {
			t.Fatal(err)
		}
		if row.RowCount != 0 {
			t.Fatalf("unknown customer must aggregate to 0 rows, got %d", row.RowCount)
		}
	})

	t.Run("MyOrdersSummary groups ecommerce orders only", func(t *testing.T) {
		q := db.New(tdb)
		row, err := q.MyOrdersSummary(ctx, 999999)
		if err != nil {
			t.Fatal(err)
		}
		if row.PendingCount+row.ProcessingCount+row.ShippingCount+row.DeliveredCount+row.CancelledCount != 0 {
			t.Fatalf("unknown customer must have zero summary counts: %+v", row)
		}
	})
}
