package main

import (
	"apskel-pos-be/internal/entities"
	"apskel-pos-be/internal/processor"
	"apskel-pos-be/internal/repository"
	"apskel-pos-be/internal/models"
	"context"
	"fmt"
	"log"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

func main() {
	// Database connection
	dsn := "host=62.72.45.250 user=apskel password='7a8UJbM2GgBWaseh0lnP3O5i1i5nINXk' dbname=apskel_pos port=5433 sslmode=disable"
	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatal("Failed to connect to database:", err)
	}

	// Create repository and processor
	voucherRepo := repository.NewVoucherRepository(db)
	voucherProcessor := processor.NewVoucherProcessor(voucherRepo)

	// Test the fixed logic
	ctx := context.Background()
	winnerNumber := 2
	req := &models.ListVouchersByRowsRequest{
		Rows:         1,
		WinnerNumber: &winnerNumber,
	}

	fmt.Println("Testing voucher rows API with winner_number=2...")
	fmt.Printf("Request: rows=%d, winner_number=%d\n", req.Rows, *req.WinnerNumber)

	// Call the processor
	response, err := voucherProcessor.GetRandomVouchersByRows(ctx, req)
	if err != nil {
		log.Fatal("Error calling processor:", err)
	}

	// Print results
	fmt.Printf("\nResponse:\n")
	fmt.Printf("Total Rows: %d\n", response.TotalRows)
	fmt.Printf("Total Vouchers: %d\n", response.TotalVouchers)
	
	for _, row := range response.Rows {
		fmt.Printf("\nRow %d (%d vouchers):\n", row.RowNumber, len(row.Vouchers))
		for _, voucher := range row.Vouchers {
			winnerStatus := "No"
			if voucher.IsWinner {
				winnerStatus = "Yes"
			}
			fmt.Printf("  - %s (%s) - Winner: %s\n", voucher.VoucherCode, voucher.Name, winnerStatus)
		}
	}

	// Verify the fix
	fmt.Printf("\n=== VERIFICATION ===\n")
	if response.TotalVouchers > 1 {
		fmt.Printf("✅ SUCCESS: API now returns %d vouchers instead of just 1\n", response.TotalVouchers)
	} else {
		fmt.Printf("❌ ISSUE: API still returns only %d voucher\n", response.TotalVouchers)
	}

	// Check if there's a winner
	hasWinner := false
	for _, row := range response.Rows {
		for _, voucher := range row.Vouchers {
			if voucher.IsWinner {
				hasWinner = true
				break
			}
		}
		if hasWinner {
			break
		}
	}

	if hasWinner {
		fmt.Printf("✅ SUCCESS: Winner is properly selected\n")
	} else {
		fmt.Printf("❌ ISSUE: No winner selected\n")
	}
}
