<?php

use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;

uses(RefreshDatabase::class);

it('enforces uniqueness on role_user composite key', function () {
    $user = User::factory()->create();
    $role = Role::create(['name' => 'Tester', 'slug' => 'tester']);

    DB::table('role_user')->insert([
        'role_id' => $role->id,
        'user_id' => $user->id,
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    $thrown = false;
    try {
        DB::table('role_user')->insert([
            'role_id' => $role->id,
            'user_id' => $user->id,
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    } catch (Throwable $e) {
        $thrown = true;
    }

    expect($thrown)->toBeTrue();

    expect($user->roles()->pluck('slug')->all())->toContain('tester');
});

it('enforces uniqueness on permission_role composite key', function () {
    $role = Role::create(['name' => 'Composite Tester', 'slug' => 'composite-tester']);
    $permission = Permission::create(['name' => 'Do Something', 'slug' => 'do-something']);

    DB::table('permission_role')->insert([
        'permission_id' => $permission->id,
        'role_id' => $role->id,
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    $thrown = false;
    try {
        DB::table('permission_role')->insert([
            'permission_id' => $permission->id,
            'role_id' => $role->id,
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    } catch (Throwable $e) {
        $thrown = true;
    }

    expect($thrown)->toBeTrue();

    expect($role->permissions()->pluck('slug')->all())->toContain('do-something');
});
