<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Tenant;
use App\Models\Tenant\PurchaseRequisition;
use App\Models\Tenant\ProductVariant;
use App\Models\Tenant\Supplier;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;

class SeedRequisition extends Command
{
    protected $signature = 'tenant:seed-requisition';
    protected $description = 'Seed a test purchase requisition for the first tenant';

    public function handle()
    {
        $tenant = Tenant::first();
        if (!$tenant) {
            $this->error('No tenant found!');
            return;
        }

        $this->info("Seeding requisition for tenant: {$tenant->name}");

        // Switch DB
        Config::set('database.connections.tenant.database', $tenant->database_name);
        DB::purge('tenant');
        DB::reconnect('tenant');
        DB::setDefaultConnection('tenant');

        // Create Supplier if none
        $supplier = Supplier::firstOrCreate(
            ['name' => 'Test Supplier'],
            ['contact' => '1234567890', 'email' => 'supplier@test.com']
        );

        // Get some variants
        $variants = ProductVariant::inRandomOrder()->limit(3)->get();
        if ($variants->isEmpty()) {
            $this->error('No products found to add to requisition.');
            return;
        }

        DB::transaction(function () use ($supplier, $variants) {
            $requisition = PurchaseRequisition::create([
                'requisition_no' => 'PR-TEST-' . rand(1000, 9999),
                'supplier_id' => $supplier->id,
                'purpose' => 'Low Stock',
                'total_amount' => 0,
                'status' => 'pending',
                'note' => 'Auto-generated test requisition',
                'created_by' => 1, // Assuming admin/user ID 1 exists
            ]);

            $total = 0;
            foreach ($variants as $variant) {
                $qty = rand(5, 20);
                $cost = $variant->cost > 0 ? $variant->cost : rand(10, 100);
                $lineTotal = $qty * $cost;
                
                $requisition->items()->create([
                    'product_variant_id' => $variant->id,
                    'quantity' => $qty,
                    'cost_price' => $cost,
                    'total' => $lineTotal,
                ]);
                
                $total += $lineTotal;
            }

            $requisition->update(['total_amount' => $total]);
            $this->info("Created Requisition #{$requisition->requisition_no} with Total: $" . number_format($total, 2));
        });
    }
}
