<?php

namespace Tests\Feature;

use App\Domains\Billing\Models\PaymentRequest;
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 IntegrationsApiTest extends TestCase
{
    use RefreshDatabase;

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

        /** @var User $user */
        $user = app(RegisterTenantAction::class)->execute([
            'company_name' => 'Integrations Demo Co',
            'full_name' => 'Tarek Nader',
            'email' => 'tarek@example.com',
            'password' => 'Password123!',
            'country' => 'LB',
            'phone' => '+96179999999',
        ]);

        $this->actingAs($user)->getJson('/api/channels')->assertOk()->assertJsonCount(2, 'data');
        $this->actingAs($user)->getJson('/api/payment/providers')->assertOk()->assertJsonCount(1, 'data');
    }

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

        /** @var User $user */
        $user = app(RegisterTenantAction::class)->execute([
            'company_name' => 'Integrations Demo Co',
            'full_name' => 'Tarek Nader',
            'email' => 'tarek@example.com',
            'password' => 'Password123!',
            'country' => 'LB',
            'phone' => '+96179999999',
        ]);

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

        $this->actingAs($user)
            ->postJson("/api/orders/{$order->id}/payment-requests")
            ->assertCreated();

        /** @var PaymentRequest $paymentRequest */
        $paymentRequest = PaymentRequest::query()->where('order_id', $order->id)->firstOrFail();

        $this->postJson('/api/payment/webhooks/whish', [
            'external_reference' => $paymentRequest->external_reference,
            'provider_reference' => 'whish-demo-ref',
            'status' => 'paid',
            'amount' => 1000,
            'currency_code' => 'USD',
        ])->assertOk();

        $this->assertDatabaseHas('payment_requests', [
            'id' => $paymentRequest->id,
            'status' => 'succeeded',
        ]);

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