<?php

namespace Tests\Feature;

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 TenantLifecycleAdminTest extends TestCase
{
    use RefreshDatabase;

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

        /** @var User $owner */
        $owner = app(RegisterTenantAction::class)->execute([
            'company_name' => 'Tenant Detail Co',
            'full_name' => 'Owner User',
            'email' => 'owner@example.com',
            'password' => 'Password123!',
            'country' => 'LB',
            'phone' => '+96170000001',
        ]);

        /** @var Tenant $tenant */
        $tenant = Tenant::query()->findOrFail($owner->tenant_id);

        $this->actingAs($owner)
            ->getJson("/api/admin/tenants/{$tenant->id}")
            ->assertOk()
            ->assertJsonPath('data.companyName', 'Tenant Detail Co');
    }

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

        /** @var User $owner */
        $owner = app(RegisterTenantAction::class)->execute([
            'company_name' => 'Tenant Detail Co',
            'full_name' => 'Owner User',
            'email' => 'owner@example.com',
            'password' => 'Password123!',
            'country' => 'LB',
            'phone' => '+96170000001',
        ]);

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

        $this->actingAs($owner)
            ->postJson("/api/admin/tenants/{$tenant->id}/sync-lifecycle")
            ->assertOk()
            ->assertJsonPath('data.status', 'past_due');
    }
}
