<?php

namespace Tests\Feature\Api;

use App\Models\User;
use App\Modules\Tenant\Models\Company;
use Database\Seeders\SaasCoreSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

class SaasCoreTest extends TestCase
{
    use RefreshDatabase;

    public function test_public_plans_endpoint_returns_seeded_plans(): void
    {
        $this->seed(SaasCoreSeeder::class);

        $this->getJson('/api/v1/plans')
            ->assertOk()
            ->assertJsonPath('success', true)
            ->assertJsonCount(3, 'data')
            ->assertJsonPath('data.0.slug', 'starter');
    }

    public function test_authenticated_user_can_create_company_with_starter_subscription(): void
    {
        $this->seed(SaasCoreSeeder::class);
        $user = User::factory()->create();

        Sanctum::actingAs($user);

        $response = $this->postJson('/api/v1/companies', [
            'name' => 'ABC Grocery',
            'email' => 'owner@example.com',
            'currency' => 'BDT',
            'timezone' => 'Asia/Dhaka',
        ]);

        $response
            ->assertCreated()
            ->assertJsonPath('success', true)
            ->assertJsonPath('data.name', 'ABC Grocery')
            ->assertJsonPath('data.subscription.plan.slug', 'starter');

        $this->assertDatabaseHas('companies', [
            'slug' => 'abc-grocery',
        ]);

        $this->assertDatabaseHas('company_user', [
            'user_id' => $user->id,
            'role' => 'owner',
        ]);

        $this->assertDatabaseHas('subscriptions', [
            'status' => 'trialing',
        ]);
    }

    public function test_tenant_middleware_requires_company_header(): void
    {
        Sanctum::actingAs(User::factory()->create());

        $this->getJson('/api/v1/tenant/current')
            ->assertStatus(422)
            ->assertJsonPath('message', 'X-Company-ID header is required');
    }

    public function test_tenant_middleware_resolves_current_company_for_member(): void
    {
        $user = User::factory()->create();
        $company = Company::query()->create([
            'name' => 'Rahman Electronics',
            'slug' => 'rahman-electronics',
            'status' => 'active',
        ]);
        $company->users()->attach($user->id, [
            'role' => 'owner',
            'joined_at' => now(),
        ]);

        Sanctum::actingAs($user);

        $this->withHeader('X-Company-ID', (string) $company->id)
            ->getJson('/api/v1/tenant/current')
            ->assertOk()
            ->assertJsonPath('data.company.slug', 'rahman-electronics');
    }
}
