<?php

namespace Tests\Feature;

use Tests\TestCase;
use App\Models\User;
use App\Models\AuctionVehicle;
use App\Models\Bid;
use App\Models\Order;
use App\Models\Vehicle;
use App\Services\Calculator\BangladeshLandedCostCalculator;

class MotoSolutionPlatformTest extends TestCase
{
    public function test_public_pages_load_successfully(): void
    {
        $pages = [
            '/',
            '/inventory',
            '/auction',
            '/calculator',
            '/preorder',
            '/how-it-works',
            '/about',
            '/services',
            '/faq',
            '/auction-sheet',
            '/contact',
            '/blog',
            '/sitemap.xml',
            '/robots.txt',
            '/login',
            '/register',
        ];

        foreach ($pages as $url) {
            $response = $this->get($url);
            $response->assertStatus(200);
        }
    }

    public function test_landed_cost_calculator_service_computation(): void
    {
        $calculator = app(BangladeshLandedCostCalculator::class);

        $result = $calculator->calculate([
            'price_jpy' => 2500000,
            'engine_cc' => 1797,
            'fuel_type' => 'Hybrid',
            'is_hybrid' => true,
            'year' => date('Y') - 2,
            'exchange_rate' => 0.82,
        ]);

        $this->assertArrayHasKey('total_landed_cost_bdt', $result);
        $this->assertArrayHasKey('cif_value_bdt', $result);
        $this->assertArrayHasKey('total_customs_taxes_bdt', $result);
        $this->assertArrayHasKey('payment_milestones', $result);
        $this->assertGreaterThan(0, $result['total_landed_cost_bdt']);
        $this->assertEquals(20.0, $result['depreciation_percentage']); // 2 years age depreciation
    }

    public function test_landed_cost_calculator_api_endpoint(): void
    {
        $response = $this->postJson(route('calculator.compute'), [
            'price_jpy' => 3000000,
            'engine_cc' => 2000,
            'fuel_type' => 'Petrol',
            'is_hybrid' => false,
            'year' => date('Y') - 3,
            'exchange_rate' => 0.82,
        ]);

        $response->assertStatus(200);
        $response->assertJsonPath('success', true);
        $this->assertNotNull($response->json('data.total_landed_cost_bdt'));
    }

    public function test_customer_portal_requires_authentication(): void
    {
        $response = $this->get(route('customer.dashboard'));
        $response->assertRedirect(route('login'));
    }

    public function test_admin_portal_requires_admin_role(): void
    {
        // Unauthenticated
        $this->get(route('admin.dashboard'))->assertRedirect(route('login'));

        // Customer user should be forbidden
        $customerUser = User::where('role', 'customer')->first();
        if ($customerUser) {
            $this->actingAs($customerUser)
                ->get(route('admin.dashboard'))
                ->assertStatus(403);
        }
    }

    public function test_customer_can_authorize_bid_and_admin_can_approve(): void
    {
        $customerUser = User::where('role', 'customer')->first();
        $adminUser = User::where('role', 'super_admin')->first();
        $auctionVehicle = AuctionVehicle::whereIn('status', ['live', 'upcoming'])->first() ?? AuctionVehicle::first();
        $auctionVehicle->update(['status' => 'live', 'auction_ends_at' => now()->addDays(2)]);

        $this->assertNotNull($customerUser);
        $this->assertNotNull($adminUser);
        $this->assertNotNull($auctionVehicle);

        // 1. Customer places bid authorization
        $response = $this->actingAs($customerUser)->post(route('auction.bid', $auctionVehicle->id), [
            'max_bid_jpy' => $auctionVehicle->starting_bid_jpy + 300000,
            'terms' => '1',
        ]);

        $response->assertSessionHas('success');

        $bid = Bid::where('user_id', $customerUser->id)
            ->where('auction_vehicle_id', $auctionVehicle->id)
            ->orderBy('id', 'desc')
            ->first();

        $this->assertNotNull($bid);
        $this->assertEquals('pending', $bid->status);

        // 2. Admin approves and dispatches to Japan floor API
        $approveResponse = $this->actingAs($adminUser)->post(route('admin.bids.approve', $bid->id), [
            'notes' => 'Client verified by phone and deposit confirmed.',
        ]);

        $approveResponse->assertSessionHas('success');
        $bid->refresh();
        $this->assertEquals('submitted', $bid->status);

        // 3. Admin marks auction as won with hammer price
        $wonResponse = $this->actingAs($adminUser)->post(route('admin.bids.won', $bid->id), [
            'won_hammer_price_jpy' => $bid->max_bid_jpy - 50000,
            'notes' => 'Won below ceiling! Savings passed to customer.',
        ]);

        $wonResponse->assertRedirect();
        $bid->refresh();
        $this->assertEquals('won', $bid->status);

        // 4. Order created with 12-step tracking
        $order = Order::where('bid_id', $bid->id)->first();
        $this->assertNotNull($order);
        $this->assertEquals('auction_won', $order->status);
    }
}
