<?php

namespace Tests\Feature;

use App\Domains\Billing\Actions\SyncTenantLifecycleAction;
use App\Domains\Channels\Models\WebhookEvent;
use App\Domains\Identity\Actions\RegisterTenantAction;
use App\Domains\Tenancy\Models\Tenant;
use App\Models\User;
use Database\Seeders\PermissionSeeder;
use Database\Seeders\PlanSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class LifecycleWebhookApiTest extends TestCase
{
    use RefreshDatabase;

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

        /** @var User $user */
        $user = app(RegisterTenantAction::class)->execute([
            'company_name' => 'Lifecycle Demo Co',
            'full_name' => 'Rita Helou',
            'email' => 'rita@example.com',
            'password' => 'Password123!',
            'country' => 'LB',
            'phone' => '+96173333333',
        ]);

        /** @var WebhookEvent $event */
        $event = WebhookEvent::query()->where('tenant_id', $user->tenant_id)->firstOrFail();
        $event->update([
            'processing_status' => 'failed',
            'error_message' => 'Temporary parsing failure',
        ]);

        $this->actingAs($user)
            ->getJson("/api/webhook-events/{$event->id}")
            ->assertOk()
            ->assertJsonPath('data.status', 'failed');

        $this->actingAs($user)
            ->postJson("/api/webhook-events/{$event->id}/retry")
            ->assertOk()
            ->assertJsonPath('data.status', 'processed');
    }

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

        /** @var User $user */
        $user = app(RegisterTenantAction::class)->execute([
            'company_name' => 'Lifecycle Demo Co',
            'full_name' => 'Rita Helou',
            'email' => 'rita@example.com',
            'password' => 'Password123!',
            'country' => 'LB',
            'phone' => '+96173333333',
        ]);

        /** @var Tenant $tenant */
        $tenant = Tenant::query()->findOrFail($user->tenant_id);
        $tenant->update([
            'trial_ends_at' => now()->subDay(),
            'status' => 'trial',
        ]);

        app(SyncTenantLifecycleAction::class)->execute($tenant->fresh());

        $this->assertDatabaseHas('tenants', [
            'id' => $tenant->id,
            'status' => 'past_due',
        ]);
    }
}
