<?php

namespace App\Console\Commands;

use App\Models\Order;
use Illuminate\Console\Command;

class TestOrderNumberCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'test:order-numbers {count=5}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Test order number generation for uniqueness';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $count = (int) $this->argument('count');

        $this->info("Testing order number generation ({$count} numbers)...");

        $orderNumbers = [];

        for ($i = 1; $i <= $count; $i++) {
            $orderNumber = Order::generateOrderNumber();
            $orderNumbers[] = $orderNumber;
            $this->info("Generated #{$i}: {$orderNumber}");

            // Small delay to test timestamp-based fallback
            usleep(100000); // 0.1 second
        }

        // Check for duplicates
        $duplicates = array_diff_assoc($orderNumbers, array_unique($orderNumbers));

        if (empty($duplicates)) {
            $this->info("✅ All order numbers are unique!");
        } else {
            $this->error("❌ Found duplicate order numbers:");
            foreach ($duplicates as $duplicate) {
                $this->error("  - {$duplicate}");
            }
        }

        // Test database uniqueness
        $this->info("\nTesting database uniqueness constraint...");

        try {
            $testOrderNumber = $orderNumbers[0]; // Use first generated number

            // Try to create two orders with the same number (should fail)
            $order1 = new Order([
                'order_number' => $testOrderNumber,
                'customer_id' => 1,
                'status' => 'created',
                'total_amount' => 100,
                'final_amount' => 100,
                'created_by' => 1,
            ]);
            $order1->save();
            $this->info("First order created successfully");

            $order2 = new Order([
                'order_number' => $testOrderNumber,
                'customer_id' => 1,
                'status' => 'created',
                'total_amount' => 200,
                'final_amount' => 200,
                'created_by' => 1,
            ]);
            $order2->save();

            $this->error("❌ Database constraint failed - duplicate order number was allowed!");

        } catch (\Illuminate\Database\QueryException $e) {
            if (str_contains($e->getMessage(), 'UNIQUE constraint failed')) {
                $this->info("✅ Database uniqueness constraint working correctly!");
            } else {
                $this->error("❌ Unexpected database error: " . $e->getMessage());
            }
        }

        return 0;
    }
}
