<?php

namespace Tests\Feature\Auth;

use App\Domains\Auth\Models\LoginAttempt;
use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Authorization\Models\Role;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Tests\TestCase;

class AdminAppLoginControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_it_logs_in_a_tenant_bound_adminapp_user(): void
    {
        $tenant = $this->createTenant();
        $this->createRole(RoleCode::AdminApp);
        $user = User::factory()->create([
            'email' => 'admin@example.com',
            'password' => Hash::make('secret123'),
            'rol_codigo' => RoleCode::AdminApp->value,
            'tenant_codigo' => $tenant->codigo,
        ]);

        $response = $this->postJson('/api/v1/adminapp/login', [
            'email' => ' ADMIN@EXAMPLE.COM ',
            'password' => 'secret123',
        ]);

        $response
            ->assertOk()
            ->assertJsonPath('code', 'auth.login_success')
            ->assertJsonPath('token_type', 'Bearer')
            ->assertJsonPath('user.id', $user->id)
            ->assertJsonPath('user.rol_codigo', RoleCode::AdminApp->value)
            ->assertJsonPath('user.tenant_codigo', $tenant->codigo);

        $this->assertNotEmpty($response->json('token'));
        $this->assertSame(['adminapp'], $user->tokens()->sole()->abilities);
        $this->assertDatabaseHas('login_attempts', [
            'user_id' => $user->id,
            'tenant_codigo' => $tenant->codigo,
            'outcome' => LoginAttempt::OUTCOME_SUCCESS,
        ]);
    }

    public function test_it_rejects_non_adminapp_users_as_invalid_credentials(): void
    {
        $this->createRole(RoleCode::User);
        $user = User::factory()->create([
            'email' => 'customer@example.com',
            'password' => Hash::make('secret123'),
            'rol_codigo' => RoleCode::User->value,
        ]);

        $this->postJson('/api/v1/adminapp/login', [
            'email' => $user->email,
            'password' => 'secret123',
        ])->assertUnprocessable()->assertJsonValidationErrors(['email']);

        $this->assertDatabaseCount('personal_access_tokens', 0);
        $this->assertSame(0, $user->refresh()->failed_login_attempts);
    }

    public function test_the_storefront_login_rejects_adminapp_users(): void
    {
        $tenant = $this->createTenant();
        $this->createRole(RoleCode::AdminApp);
        $user = User::factory()->create([
            'email' => 'admin@example.com',
            'password' => Hash::make('secret123'),
            'rol_codigo' => RoleCode::AdminApp->value,
            'tenant_codigo' => $tenant->codigo,
        ]);

        $this->postJson('/api/login', [
            'email' => $user->email,
            'password' => 'secret123',
            'tenant_codigo' => $tenant->codigo,
        ])->assertUnprocessable()->assertJsonValidationErrors(['email']);

        $this->assertDatabaseCount('personal_access_tokens', 0);
    }

    public function test_it_rejects_an_adminapp_user_without_a_tenant(): void
    {
        $this->createRole(RoleCode::AdminApp);
        $user = User::factory()->create([
            'email' => 'unbound@example.com',
            'password' => Hash::make('secret123'),
            'rol_codigo' => RoleCode::AdminApp->value,
            'tenant_codigo' => null,
        ]);

        $this->postJson('/api/v1/adminapp/login', [
            'email' => $user->email,
            'password' => 'secret123',
        ])->assertUnprocessable()->assertJsonValidationErrors(['email']);

        $this->assertDatabaseCount('personal_access_tokens', 0);
    }

    public function test_it_validates_required_fields(): void
    {
        $this->postJson('/api/v1/adminapp/login', [])
            ->assertUnprocessable()
            ->assertJsonValidationErrors(['email', 'password']);
    }

    private function createRole(RoleCode $role): Role
    {
        return Role::query()->create([
            'codigo' => $role->value,
            'nombre' => $role->value,
        ]);
    }

    private function createTenant(): Tenant
    {
        return Tenant::query()->create([
            'codigo' => 'acme',
            'nombre' => 'Acme',
            'dominio' => 'acme.test',
        ]);
    }
}
