<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\User;
use App\Models\AuctionVehicle;
use App\Models\Bid;
use App\Models\BidHistory;
use App\Services\Calculator\BangladeshLandedCostCalculator;
use Illuminate\Support\Str;

class BidSeeder extends Seeder
{
    public function run(): void
    {
        $calculator = app(BangladeshLandedCostCalculator::class);
        $customers = User::where('role', 'customer')->get();
        $vehicles = AuctionVehicle::all();
        $admin = User::where('role', 'super_admin')->first();

        if ($customers->isEmpty() || $vehicles->isEmpty()) {
            return;
        }

        $bidsConfig = [
            // Pending review by admin (5 bids)
            ['cust_idx' => 0, 'veh_idx' => 0, 'add_jpy' => 150000, 'status' => 'pending'],
            ['cust_idx' => 1, 'veh_idx' => 1, 'add_jpy' => 200000, 'status' => 'pending'],
            ['cust_idx' => 2, 'veh_idx' => 3, 'add_jpy' => 100000, 'status' => 'pending'],
            ['cust_idx' => 5, 'veh_idx' => 6, 'add_jpy' => 120000, 'status' => 'pending'],
            ['cust_idx' => 7, 'veh_idx' => 8, 'add_jpy' => 180000, 'status' => 'pending'],

            // Approved by admin (4 bids)
            ['cust_idx' => 3, 'veh_idx' => 2, 'add_jpy' => 350000, 'status' => 'approved'],
            ['cust_idx' => 4, 'veh_idx' => 4, 'add_jpy' => 250000, 'status' => 'approved'],
            ['cust_idx' => 6, 'veh_idx' => 7, 'add_jpy' => 150000, 'status' => 'approved'],
            ['cust_idx' => 9, 'veh_idx' => 9, 'add_jpy' => 90000,  'status' => 'approved'],

            // Submitted to Japan live auction floor (5 bids)
            ['cust_idx' => 0, 'veh_idx' => 10, 'add_jpy' => 160000, 'status' => 'submitted'],
            ['cust_idx' => 1, 'veh_idx' => 11, 'add_jpy' => 180000, 'status' => 'submitted'],
            ['cust_idx' => 2, 'veh_idx' => 12, 'add_jpy' => 220000, 'status' => 'submitted'],
            ['cust_idx' => 3, 'veh_idx' => 13, 'add_jpy' => 280000, 'status' => 'submitted'],
            ['cust_idx' => 8, 'veh_idx' => 14, 'add_jpy' => 150000, 'status' => 'submitted'],

            // Won bids (4 bids)
            ['cust_idx' => 3, 'veh_idx' => 15, 'add_jpy' => 300000, 'status' => 'won'],
            ['cust_idx' => 4, 'veh_idx' => 16, 'add_jpy' => 240000, 'status' => 'won'],
            ['cust_idx' => 6, 'veh_idx' => 17, 'add_jpy' => 180000, 'status' => 'won'],
            ['cust_idx' => 0, 'veh_idx' => 18, 'add_jpy' => 210000, 'status' => 'won'],

            // Lost bids (2 bids)
            ['cust_idx' => 1, 'veh_idx' => 19, 'add_jpy' => 100000, 'status' => 'lost'],
            ['cust_idx' => 8, 'veh_idx' => 20, 'add_jpy' => 120000, 'status' => 'lost'],
        ];

        foreach ($bidsConfig as $index => $cfg) {
            $customer = $customers[$cfg['cust_idx'] % $customers->count()];
            $vehicle = $vehicles[$cfg['veh_idx'] % $vehicles->count()];
            $maxBidJpy = $vehicle->starting_bid_jpy + $cfg['add_jpy'];

            $calc = $calculator->calculate([
                'price_jpy' => $maxBidJpy,
                'engine_cc' => $vehicle->engine_cc,
                'fuel_type' => $vehicle->fuel_type,
                'is_hybrid' => str_contains(strtolower($vehicle->fuel_type), 'hybrid'),
                'year' => $vehicle->year,
            ]);

            $bidCode = 'MS-BID-' . date('Y') . '-' . str_pad($index + 1, 4, '0', STR_PAD_LEFT);

            $bid = Bid::updateOrCreate(
                ['bid_code' => $bidCode],
                [
                    'user_id' => $customer->id,
                    'auction_vehicle_id' => $vehicle->id,
                    'max_bid_jpy' => $maxBidJpy,
                    'exchange_rate' => $calc['exchange_rate'],
                    'estimated_bd_cost_bdt' => $calc['total_landed_cost_bdt'],
                    'currency' => 'JPY',
                    'cost_breakdown_snapshot' => $calc,
                    'status' => $cfg['status'],
                    'terms_accepted' => true,
                    'terms_accepted_at' => now()->subHours(rand(2, 48)),
                    'ip_address' => '103.205.' . rand(10, 250) . '.' . rand(1, 250),
                    'user_agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)',
                    'reviewed_by' => in_array($cfg['status'], ['approved', 'submitted', 'won', 'lost']) ? $admin->id : null,
                    'reviewed_at' => in_array($cfg['status'], ['approved', 'submitted', 'won', 'lost']) ? now()->subHours(rand(1, 24)) : null,
                    'admin_notes' => in_array($cfg['status'], ['approved', 'submitted', 'won', 'lost']) ? 'Customer verified by phone and booking terms approved.' : null,
                    'japan_api_provider' => in_array($cfg['status'], ['submitted', 'won', 'lost']) ? 'App\Services\Auction\MockJapanAuctionProvider' : null,
                    'japan_api_bid_id' => in_array($cfg['status'], ['submitted', 'won', 'lost']) ? 'JP-TX-' . strtoupper(Str::random(8)) : null,
                    'japan_api_status' => in_array($cfg['status'], ['submitted', 'won', 'lost']) ? 'CONFIRMED' : null,
                    'japan_api_submitted_at' => in_array($cfg['status'], ['submitted', 'won', 'lost']) ? now()->subHours(rand(1, 12)) : null,
                    'won_hammer_price_jpy' => $cfg['status'] === 'won' ? ($maxBidJpy - rand(30000, 80000)) : null,
                    'final_bd_cost_bdt' => $cfg['status'] === 'won' ? ($calc['total_landed_cost_bdt'] - 45000) : null,
                ]
            );

            // Create bid timeline history
            BidHistory::firstOrCreate(
                ['bid_id' => $bid->id, 'action' => 'created'],
                [
                    'user_id' => $customer->id,
                    'from_status' => null,
                    'to_status' => 'pending',
                    'notes' => "Customer authorized maximum bid of ¥" . number_format($maxBidJpy, 0) . " with estimated landed cost ৳" . number_format($calc['total_landed_cost_bdt'], 0),
                    'ip_address' => $bid->ip_address,
                ]
            );

            if (in_array($cfg['status'], ['approved', 'submitted', 'won', 'lost'])) {
                BidHistory::firstOrCreate(
                    ['bid_id' => $bid->id, 'action' => 'approved'],
                    [
                        'user_id' => $admin->id,
                        'from_status' => 'pending',
                        'to_status' => 'approved',
                        'notes' => 'Customer credentials and bidding authorization verified by MotoSolution management.',
                        'ip_address' => '127.0.0.1',
                    ]
                );
            }

            if (in_array($cfg['status'], ['submitted', 'won', 'lost'])) {
                BidHistory::firstOrCreate(
                    ['bid_id' => $bid->id, 'action' => 'submitted_to_japan'],
                    [
                        'user_id' => $admin->id,
                        'from_status' => 'approved',
                        'to_status' => 'submitted',
                        'notes' => 'Dispatched through Japan Auction API gateway for live floor bidding.',
                        'ip_address' => '127.0.0.1',
                    ]
                );
            }
        }
    }
}
