<?php

namespace Tests\Unit\Services\Dashboard;

use App\Models\User;
use App\Services\Dashboard\DashboardRouteService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

class DashboardRouteServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_resolve_returns_fallback_when_no_roles(): void
    {
        $user = User::query()->create([
            'firstname' => 'No',
            'lastname' => 'Role',
            'email' => 'norole@example.com',
            'cellphone' => '5555555555',
            'address_street' => '123 Main',
            'city' => 'City',
            'state' => 'ST',
            'zip' => '12345',
            'accept_school_policy' => 1,
            'status' => 'Active',
            'password' => bcrypt('secret'),
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

        $service = app(DashboardRouteService::class);
        $payload = $service->resolveForUser($user);

        $this->assertSame('/landing_page/guest_dashboard', $payload['route']);
    }

    public function test_resolve_returns_dashboard_route_for_role(): void
    {
        $roleId = DB::table('roles')->insertGetId([
            'name' => 'administrator',
            'dashboard_route' => '/administrator/dashboard',
            'priority' => 1,
            'is_active' => 1,
        ]);

        $user = User::query()->create([
            'firstname' => 'Admin',
            'lastname' => 'User',
            'email' => 'admin@example.com',
            'cellphone' => '5555555555',
            'address_street' => '123 Main',
            'city' => 'City',
            'state' => 'ST',
            'zip' => '12345',
            'accept_school_policy' => 1,
            'status' => 'Active',
            'password' => bcrypt('secret'),
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

        DB::table('user_roles')->insert([
            'user_id' => $user->id,
            'role_id' => $roleId,
        ]);

        $service = app(DashboardRouteService::class);
        $payload = $service->resolveForUser($user);

        $this->assertSame('/administrator/dashboard', $payload['route']);
        $this->assertSame('administrator', strtolower((string) $payload['role']));
    }
}
