<?php

namespace Tests\Feature;

use App\Domains\Identity\Actions\RegisterTenantAction;
use App\Domains\Leads\Models\Lead;
use App\Domains\Leads\Models\PipelineStage;
use App\Models\User;
use Database\Seeders\PermissionSeeder;
use Database\Seeders\PlanSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class LeadsApiTest extends TestCase
{
    use RefreshDatabase;

    public function test_registered_tenant_has_seeded_leads_and_can_fetch_them(): void
    {
        $this->seed([
            PlanSeeder::class,
            PermissionSeeder::class,
        ]);

        /** @var User $user */
        $user = app(RegisterTenantAction::class)->execute([
            'company_name' => 'Leads Demo Co',
            'full_name' => 'Nadine Aziz',
            'email' => 'nadine@example.com',
            'password' => 'Password123!',
            'country' => 'LB',
            'phone' => '+96175555555',
        ]);

        $this->assertDatabaseCount('leads', 3);

        $this->actingAs($user)
            ->getJson('/api/leads')
            ->assertOk()
            ->assertJsonCount(3, 'data');
    }

    public function test_user_can_move_a_lead_to_a_new_stage(): void
    {
        $this->seed([
            PlanSeeder::class,
            PermissionSeeder::class,
        ]);

        /** @var User $user */
        $user = app(RegisterTenantAction::class)->execute([
            'company_name' => 'Leads Demo Co',
            'full_name' => 'Nadine Aziz',
            'email' => 'nadine@example.com',
            'password' => 'Password123!',
            'country' => 'LB',
            'phone' => '+96175555555',
        ]);

        /** @var Lead $lead */
        $lead = Lead::query()->where('tenant_id', $user->tenant_id)->firstOrFail();
        /** @var PipelineStage $targetStage */
        $targetStage = PipelineStage::query()
            ->where('tenant_id', $user->tenant_id)
            ->where('name', 'Won')
            ->firstOrFail();

        $this->actingAs($user)
            ->postJson("/api/leads/{$lead->id}/move-stage", [
                'stage_id' => $targetStage->id,
            ])
            ->assertOk()
            ->assertJsonPath('data.stageName', 'Won')
            ->assertJsonPath('data.status', 'won');

        $this->assertDatabaseHas('leads', [
            'id' => $lead->id,
            'stage_id' => $targetStage->id,
            'status' => 'won',
        ]);
    }
}
