<?php

namespace Tests\Feature;

use App\Models\Central\Company;
use App\Models\Central\Plan;
use App\Models\Tenant\Client;
use App\Models\Tenant\User;
use App\Models\Tenant\Vehicle;
use App\Models\Tenant\WorkOrder;
use App\Tenancy\TenantManager;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class WorkOrderDashboardTest extends TestCase
{
    use RefreshDatabase;

    public function test_dashboard_page_returns_200(): void
    {
        $plan = Plan::firstOrCreate(['slug' => 'test'], ['name' => 'T', 'price' => 0, 'features' => []]);
        $company = Company::create([
            'plan_id' => $plan->id, 'slug' => 'dash-' . uniqid(),
            'name' => 'Dash Co', 'status' => 'active',
        ]);
        app(TenantManager::class)->setCurrent($company);

        $user = User::create([
            'company_id' => $company->id,
            'name' => 'Test Owner', 'email' => 'o-' . uniqid() . '@x.com',
            'password' => bcrypt('secret'), 'role' => 'owner', 'status' => 'active',
        ]);

        $client = Client::create([
            'company_id' => $company->id, 'name' => 'C', 'phone' => '+000',
        ]);
        $vehicle = Vehicle::create([
            'company_id' => $company->id, 'client_id' => $client->id,
            'make' => 'BMW', 'model' => 'X5', 'plate' => 'CIU 001',
        ]);
        $wo = WorkOrder::create([
            'company_id' => $company->id,
            'number' => 'WO-TEST-001',
            'client_id' => $client->id, 'vehicle_id' => $vehicle->id,
            'opened_at' => now(), 'status' => 'in_work', 'total' => 100,
        ]);

        $this->withoutExceptionHandling();
        // Simulate tenant subdomain — ResolveTenant reads Host from Request::getHost()
        $slug = $company->slug;
        $central = config('app.central_domain') ?: 'service.mir.md';
        $resp = $this->actingAs($user, 'web')
            ->get("http://{$slug}.{$central}/app/work-orders/{$wo->id}/dashboard");
        // Follow redirect chain (auth/session bootstrap can bounce twice)
        for ($i = 0; $i < 3 && $resp->isRedirection(); $i++) {
            $resp = $this->actingAs($user, 'web')->get($resp->headers->get('Location'));
        }

        $this->assertNotEquals(404, $resp->status(), 'Dashboard returned 404 — route or record binding broken');
        $this->assertNotEquals(500, $resp->status(), 'Dashboard returned 500 — server error in mount/render');
        $resp->assertOk();
    }
}
