<?php

namespace Tests\Feature;

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

class TrackingApprovalTest extends TestCase
{
    use RefreshDatabase;

    private Company $company;
    private WorkOrder $wo;

    protected function setUp(): void
    {
        parent::setUp();
        $plan = Plan::firstOrCreate(['slug' => 'test'], ['name' => 'T', 'price' => 0, 'features' => []]);
        $this->company = Company::create(['plan_id' => $plan->id, 'slug' => 'trk-' . uniqid(), 'name' => 'Trk Co', 'status' => 'active']);
        app(TenantManager::class)->setCurrent($this->company);
        $client = Client::create(['name' => 'Cli', 'phone' => '+37399123456', 'type' => 'individual', 'status' => 'active']);
        $vehicle = Vehicle::create(['client_id' => $client->id, 'make' => 'BMW', 'model' => 'X5', 'plate' => 'TRK-1']);
        $this->wo = WorkOrder::create([
            'number' => WorkOrder::generateNumber($this->company->id),
            'client_id' => $client->id, 'vehicle_id' => $vehicle->id,
            'opened_at' => today(), 'status' => 'in_work', 'total' => 5000,
        ]);
    }

    public function test_creating_work_with_requires_approval_generates_token(): void
    {
        $work = WorkOrderWork::create([
            'work_order_id' => $this->wo->id,
            'name' => 'Înlocuire amortizor față stâng',
            'hours' => 1.5, 'price_per_hour' => 420, 'status' => 'todo',
            'requires_approval' => true,
        ]);

        $this->assertNotEmpty($work->approval_token);
        $this->assertEquals(24, strlen($work->approval_token));
        $this->assertTrue($work->isPendingApproval());
    }

    public function test_approve_endpoint_marks_line_approved(): void
    {
        $work = WorkOrderWork::create([
            'work_order_id' => $this->wo->id,
            'name' => 'Extra labor', 'hours' => 1, 'price_per_hour' => 400,
            'status' => 'todo', 'requires_approval' => true,
        ]);
        $token = $this->wo->tracking_token;
        $lineToken = $work->approval_token;

        $resp = $this->post("/t/{$token}/approve/work/{$lineToken}", ['decision' => 'approve']);
        $resp->assertRedirect(route('tracking.show', ['token' => $token]));

        $work->refresh();
        $this->assertNotNull($work->approved_at);
        $this->assertFalse($work->isPendingApproval());
    }

    public function test_decline_endpoint_marks_line_declined(): void
    {
        $part = WorkOrderPart::create([
            'work_order_id' => $this->wo->id,
            'name' => 'Filtru extra', 'article' => 'EX-1',
            'qty' => 1, 'sell_price' => 200, 'status' => 'needed',
            'requires_approval' => true,
        ]);
        $token = $this->wo->tracking_token;

        $resp = $this->post("/t/{$token}/approve/part/{$part->approval_token}", ['decision' => 'decline']);
        $resp->assertRedirect();

        $part->refresh();
        $this->assertNull($part->approved_at);
        $this->assertNotNull($part->declined_at);
        $this->assertFalse($part->isPendingApproval());
    }

    public function test_wrong_line_token_returns_redirect_with_error(): void
    {
        WorkOrderWork::create([
            'work_order_id' => $this->wo->id,
            'name' => 'X', 'hours' => 1, 'price_per_hour' => 200,
            'status' => 'todo', 'requires_approval' => true,
        ]);
        $token = $this->wo->tracking_token;

        $resp = $this->post("/t/{$token}/approve/work/wrongtoken12345678901234");
        $resp->assertRedirect();
        // Session flashed with error
        $resp->assertSessionHas('approval_status');
        $status = session('approval_status');
        $this->assertEquals('error', $status['kind']);
    }

    public function test_already_approved_line_cannot_be_approved_again(): void
    {
        $work = WorkOrderWork::create([
            'work_order_id' => $this->wo->id,
            'name' => 'Already approved', 'hours' => 1, 'price_per_hour' => 200,
            'status' => 'todo', 'requires_approval' => true,
        ]);
        $work->update(['approved_at' => now()->subHour()]);
        $originalApproval = $work->approved_at;
        $token = $this->wo->tracking_token;

        // Second attempt should be a no-op (line no longer pending)
        $this->post("/t/{$token}/approve/work/{$work->approval_token}", ['decision' => 'approve']);

        $work->refresh();
        $this->assertEquals($originalApproval->toIso8601String(), $work->approved_at->toIso8601String());
    }

    public function test_tracking_show_includes_pending_approval_banner(): void
    {
        WorkOrderWork::create([
            'work_order_id' => $this->wo->id,
            'name' => 'Înlocuire amortizor', 'hours' => 1.5, 'price_per_hour' => 420,
            'status' => 'todo', 'requires_approval' => true,
        ]);

        $token = $this->wo->tracking_token;
        $resp = $this->get("/t/{$token}");
        $resp->assertOk();
        $resp->assertSee('Necesită aprobarea ta');
        $resp->assertSee('Înlocuire amortizor');
        $resp->assertSee('Aprob');
    }

    public function test_approved_line_does_not_appear_in_banner(): void
    {
        $work = WorkOrderWork::create([
            'work_order_id' => $this->wo->id,
            'name' => 'Should not show', 'hours' => 1, 'price_per_hour' => 200,
            'status' => 'todo', 'requires_approval' => true,
        ]);
        $work->update(['approved_at' => now()]);

        $resp = $this->get("/t/{$this->wo->tracking_token}");
        $resp->assertOk();
        $resp->assertDontSee('Should not show');
    }
}
