<?php

use App\Enums\UserStatus;
use App\Livewire\Auth\Login;
use Livewire\Livewire;
use Spatie\Permission\Models\Role;

beforeEach(function () {
    $this->setupUser([
        'username' => 'testuser',
        'email' => 'test@example.com',
        'password' => bcrypt('password123'),
        'status' => UserStatus::ACTIVE,
    ]);
});

it('renders the login page correctly', function () {
    $this->get(route('login'))
        ->assertOk()
        ->assertSeeLivewire(Login::class);
});

it('shows validation error when login field is empty', function () {
    Livewire::test(Login::class)
        ->set('form.login', '')
        ->set('form.password', 'password123')
        ->call('auth')
        ->assertHasErrors(['form.login' => 'required']);
});

it('shows validation error when password field is empty', function () {
    Livewire::test(Login::class)
        ->set('form.login', 'testuser')
        ->set('form.password', '')
        ->call('auth')
        ->assertHasErrors(['form.password' => 'required']);
});

it('shows error message on invalid credentials', function () {
    Livewire::test(Login::class)
        ->set('form.login', 'testuser')
        ->set('form.password', 'wrongpassword')
        ->call('auth');

    $this->assertGuest();
});

it('shows error message if user is inactive', function () {
    $this->user->update(['status' => UserStatus::INACTIVE]);

    Livewire::test(Login::class)
        ->set('form.login', 'testuser')
        ->set('form.password', 'password123')
        ->call('auth');

    $this->assertGuest();
});

it('can login with valid email', function () {
    Livewire::test(Login::class)
        ->set('form.login', 'test@example.com')
        ->set('form.password', 'password123')
        ->call('auth');

    $this->assertAuthenticatedAs($this->user);
});

it('can login with valid username', function () {
    Livewire::test(Login::class)
        ->set('form.login', 'testuser')
        ->set('form.password', 'password123')
        ->call('auth');

    $this->assertAuthenticatedAs($this->user);
});

it('redirects to studio dashboard for Admin role', function () {
    $role = Role::firstOrCreate(['name' => 'Admin']);
    $this->user->assignRole($role);

    Livewire::test(Login::class)
        ->set('form.login', 'testuser')
        ->set('form.password', 'password123')
        ->call('auth')
        ->assertRedirect('/studio/dashboard/overview');
});

it('redirects to member overview for Customer role', function () {
    $role = Role::firstOrCreate(['name' => 'Customer']);
    $this->user->assignRole($role);

    Livewire::test(Login::class)
        ->set('form.login', 'testuser')
        ->set('form.password', 'password123')
        ->call('auth')
        ->assertRedirect('/member/overview');
});
