<?php

use App\Enums\IsActive;
use App\Enums\RoleEnum;
use App\Filament\Resources\Master\SubLocations\Pages\ManageSubLocations;
use App\Models\Location;
use App\Models\SubLocation;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

uses(RefreshDatabase::class);

beforeEach(function () {
    $this->user = User::factory()->create(['is_active' => IsActive::ACTIVE]);

    // Setup Permissions
    Permission::firstOrCreate(['name' => 'ViewAny:SubLocation', 'guard_name' => 'web']);
    Permission::firstOrCreate(['name' => 'Create:SubLocation', 'guard_name' => 'web']);
    Permission::firstOrCreate(['name' => 'Update:SubLocation', 'guard_name' => 'web']);
    Permission::firstOrCreate(['name' => 'Delete:SubLocation', 'guard_name' => 'web']);
    Permission::firstOrCreate(['name' => 'Restore:SubLocation', 'guard_name' => 'web']);
    Permission::firstOrCreate(['name' => 'ForceDelete:SubLocation', 'guard_name' => 'web']);

    $this->user->givePermissionTo([
        'ViewAny:SubLocation',
        'Create:SubLocation',
        'Update:SubLocation',
        'Delete:SubLocation',
        'Restore:SubLocation',
        'ForceDelete:SubLocation',
    ]);
});

/*
|--------------------------------------------------------------------------
| Positive Scenarios
|--------------------------------------------------------------------------
*/

test('can render sublokus list page', function () {
    $this->actingAs($this->user);

    Livewire::test(ManageSubLocations::class)
        ->assertSuccessful();
});

test('can list sublokus', function () {
    $subLocations = SubLocation::factory()->count(5)->create();

    $this->actingAs($this->user);

    Livewire::test(ManageSubLocations::class)
        ->call('loadTable')
        ->assertCanSeeTableRecords($subLocations);
});

test('can create sublokus', function () {
    $location = Location::factory()->create(['is_active' => IsActive::ACTIVE]);

    $this->actingAs($this->user);

    Livewire::test(ManageSubLocations::class)
        ->mountAction('create')
        ->setActionData([
            'location_id' => $location->id,
            'name' => 'Sublokus Baru',
        ])
        ->callMountedAction()
        ->assertHasNoActionErrors();

    $this->assertDatabaseHas('sub_locations', [
        'location_id' => $location->id,
        'name' => 'Sublokus Baru',
    ]);
});

test('can edit sublokus', function () {
    $subLocation = SubLocation::factory()->create();
    $newLocation = Location::factory()->create(['is_active' => IsActive::ACTIVE]);

    $this->actingAs($this->user);

    Livewire::test(ManageSubLocations::class)
        ->mountTableAction('edit', $subLocation)
        ->setActionData([
            'location_id' => $newLocation->id,
            'name' => 'Sublokus Updated',
        ])
        ->callMountedTableAction()
        ->assertHasNoActionErrors();

    expect($subLocation->refresh()->name)->toBe('Sublokus Updated');
    expect($subLocation->location_id)->toBe($newLocation->id);
});

test('can toggle is_active status', function () {
    $subLocation = SubLocation::factory()->create(['is_active' => IsActive::INACTIVE]);

    $this->actingAs($this->user);

    Livewire::test(ManageSubLocations::class)
        ->call('updateTableColumnState', 'is_active', $subLocation->getKey(), true);

    expect($subLocation->refresh()->is_active)->toBe(IsActive::ACTIVE);
});

/*
|--------------------------------------------------------------------------
| Negative Scenarios (Validation & Authorization)
|--------------------------------------------------------------------------
*/

test('cannot create sublokus with invalid data', function () {
    $this->actingAs($this->user);

    // Empty name
    Livewire::test(ManageSubLocations::class)
        ->mountAction('create')
        ->setActionData(['name' => '', 'location_id' => null])
        ->callMountedAction()
        ->assertHasActionErrors(['name' => 'required', 'location_id' => 'required']);

    // Non-existent location
    Livewire::test(ManageSubLocations::class)
        ->mountAction('create')
        ->setActionData(['name' => 'Valid Name', 'location_id' => 999999])
        ->callMountedAction()
        ->assertHasActionErrors(['location_id']);
});

test('unauthorized user cannot render sublokus page', function () {
    $unauthorizedUser = User::factory()->create(['is_active' => IsActive::ACTIVE]);

    $this->actingAs($unauthorizedUser);

    Livewire::test(ManageSubLocations::class)
        ->assertForbidden();
});

test('user without update permission cannot see edit action', function () {
    $viewOnlyUser = User::factory()->create(['is_active' => IsActive::ACTIVE]);
    $viewOnlyUser->givePermissionTo('ViewAny:SubLocation');
    $subLocation = SubLocation::factory()->create();

    $this->actingAs($viewOnlyUser);

    Livewire::test(ManageSubLocations::class)
        ->assertTableActionHidden('edit', $subLocation);
});

/*
|--------------------------------------------------------------------------
| Soft Delete Scenarios
|--------------------------------------------------------------------------
*/

test('can delete sublokus', function () {
    $subLocation = SubLocation::factory()->create();

    $this->actingAs($this->user);

    Livewire::test(ManageSubLocations::class)
        ->callTableAction('delete', $subLocation);

    $this->assertSoftDeleted($subLocation);
});

test('can restore deleted sublokus', function () {
    $roleDev = Role::firstOrCreate(['name' => RoleEnum::DEVELOPER->value, 'guard_name' => 'web']);
    $this->user->assignRole($roleDev);

    $subLocation = SubLocation::factory()->create(['deleted_at' => now()]);

    $this->actingAs($this->user);

    Livewire::test(ManageSubLocations::class)
        ->filterTable('trashed', 'with')
        ->callTableAction('restore', $subLocation);

    $this->assertDatabaseHas('sub_locations', [
        'id' => $subLocation->id,
        'deleted_at' => null,
    ]);
});

test('can force delete sublokus', function () {
    $roleDev = Role::firstOrCreate(['name' => RoleEnum::DEVELOPER->value, 'guard_name' => 'web']);
    $this->user->assignRole($roleDev);

    $subLocation = SubLocation::factory()->create(['deleted_at' => now()]);

    $this->actingAs($this->user);

    Livewire::test(ManageSubLocations::class)
        ->filterTable('trashed', 'only')
        ->callTableAction('forceDelete', $subLocation);

    $this->assertDatabaseMissing('sub_locations', ['id' => $subLocation->id]);
});

test('trashed filter visibility depends on developer role', function () {
    $roleAdmin = Role::firstOrCreate(['name' => RoleEnum::ADMINISTRATOR->value, 'guard_name' => 'web']);
    $this->user->assignRole($roleAdmin);

    $this->actingAs($this->user);

    Livewire::test(ManageSubLocations::class)
        ->assertTableFilterHidden('trashed');

    $roleDev = Role::firstOrCreate(['name' => RoleEnum::DEVELOPER->value, 'guard_name' => 'web']);
    $this->user->assignRole($roleDev);

    Livewire::test(ManageSubLocations::class)
        ->assertTableFilterVisible('trashed');
});
