<?php

namespace Tests\Feature;

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

class WorkflowApiTest extends TestCase
{
    use RefreshDatabase;

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

        /** @var User $user */
        $user = app(RegisterTenantAction::class)->execute([
            'company_name' => 'Workflow Demo Co',
            'full_name' => 'Hiba Younes',
            'email' => 'hiba@example.com',
            'password' => 'Password123!',
            'country' => 'LB',
            'phone' => '+96177777777',
        ]);

        $this->actingAs($user)->getJson('/api/quotes')->assertOk()->assertJsonCount(2, 'data');
        $this->actingAs($user)->getJson('/api/tasks')->assertOk()->assertJsonCount(3, 'data');
        $this->actingAs($user)->getJson('/api/follow-up-queue')->assertOk()->assertJsonCount(3, 'data');
    }

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

        /** @var User $user */
        $user = app(RegisterTenantAction::class)->execute([
            'company_name' => 'Workflow Demo Co',
            'full_name' => 'Hiba Younes',
            'email' => 'hiba@example.com',
            'password' => 'Password123!',
            'country' => 'LB',
            'phone' => '+96177777777',
        ]);

        /** @var Order $order */
        $order = Order::query()->where('tenant_id', $user->tenant_id)->firstOrFail();

        $this->actingAs($user)
            ->postJson("/api/orders/{$order->id}/status", ['status' => 'processing'])
            ->assertOk()
            ->assertJsonPath('data.status', 'processing');

        $this->actingAs($user)
            ->postJson("/api/orders/{$order->id}/payment-status", ['payment_status' => 'paid'])
            ->assertOk()
            ->assertJsonPath('data.paymentStatus', 'paid');

        $this->assertDatabaseHas('orders', [
            'id' => $order->id,
            'status' => 'processing',
            'payment_status' => 'paid',
        ]);
    }
}
