<?php

namespace Tests\Feature\Tenant;

use App\Models\Tenant;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Tests\TestCase;

abstract class TenantTestCase extends TestCase
{
    use RefreshDatabase;

    protected Tenant $tenant;

    protected User $tenantUser;

    protected string $token;

    protected function setUp(): void
    {
        parent::setUp();

        $this->initialiseTenantContext();
    }

    protected function authenticatedRequest(string $method, string $uri, array $data = [], array $headers = [])
    {
        $headers = array_merge([
            'Authorization' => 'Bearer '.$this->token,
        ], $headers);

        return $this->withHeaders($headers)->json($method, $uri, $data);
    }

    protected function mockTenantContext(): void
    {
        $this->app->instance('tenant', $this->tenant);
    }

    protected function initialiseTenantContext(): void
    {
        $this->tenant = Tenant::factory()->create([
            'name' => 'Test Tenant',
            'slug' => 'test-tenant-'.Str::random(6),
        ]);

        $this->tenantUser = User::factory()->create([
            'name' => 'Test User',
            'email' => 'test-'.Str::random(6).'@example.com',
            'tenant_id' => $this->tenant->id,
            'role' => 'tenant_admin',
            'password' => Hash::make('password'),
        ]);

        $login = $this->postJson('/api/v1/tenant-auth/login', [
            'login' => $this->tenantUser->email,
            'password' => 'password',
        ]);

        $login->assertOk();
        $this->token = (string) $login->json('token');

        $this->app->instance('tenant', $this->tenant);
    }
}
