<?php

namespace Tests\Feature;

use App\Models\Tenant;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class AuthTest extends TestCase
{
    use RefreshDatabase;

    public function test_user_can_register_workspace(): void
    {
        $response = $this->postJson('/api/v1/auth/register', [
            'name'                  => 'John Doe',
            'email'                 => 'john@test.com',
            'password'              => 'Password123!',
            'password_confirmation' => 'Password123!',
            'workspace_name'        => 'Test Company',
        ]);

        $response->assertStatus(201)
            ->assertJsonStructure([
                'message', 'status', 'tenant' => ['id', 'name', 'slug'],
            ]);
    }

    public function test_user_can_login(): void
    {
        $tenant = Tenant::create([
            'id' => 'test-tenant-' . uniqid(),
            'name' => 'Test Tenant',
            'slug' => 'test-tenant',
            'email' => 'test-tenant@test.com',
            'status' => 'active',
        ]);
        tenancy()->initialize($tenant);

        $user = User::create([
            'name'              => 'Test User',
            'email'             => 'test@test.com',
            'password'          => bcrypt('Password123!'),
            'status'            => 'active',
            'email_verified_at' => now(),
        ]);

        $response = $this->postJson('/api/v1/auth/login', [
            'email'    => 'test@test.com',
            'password' => 'Password123!',
        ]);

        $response->assertOk()->assertJsonStructure(['token', 'user']);

        tenancy()->end();
    }

    public function test_login_with_wrong_password_returns_401(): void
    {
        $response = $this->postJson('/api/v1/auth/login', [
            'email'    => 'nonexistent@test.com',
            'password' => 'WrongPassword',
        ]);

        $response->assertStatus(401);
    }
}
