<?php

use App\Database\Seeds\DatabaseSeeder;
use CodeIgniter\Shield\Models\UserModel;
use CodeIgniter\Shield\Test\AuthenticationTesting;
use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\DatabaseTestTrait;
use CodeIgniter\Test\FeatureTestTrait;

/**
 * @internal
 */
final class DashboardAccessTest extends CIUnitTestCase
{
    use AuthenticationTesting;
    use DatabaseTestTrait;
    use FeatureTestTrait;

    protected $migrate = true;
    protected $refresh = true;
    protected $seed = DatabaseSeeder::class;
    protected $DBGroup = 'tests';
    protected $namespace = ['CodeIgniter\\Shield', 'CodeIgniter\\Settings', 'App'];

    public function testAdminSeesGlobalDashboard(): void
    {
        $admin = $this->findUserByEmail('admin@academia.local');

        $this->actingAs($admin);
        $result = $this->withSession($_SESSION)->get('/dashboard');

        $result->assertOK();
        $result->assertSee('Copii activi');
        $result->assertSee('Maria Enache');
    }

    public function testCoachDashboardIsScopedToOwnChildren(): void
    {
        $coach = $this->findUserByEmail('andrei@academia.local');

        $this->actingAs($coach);
        $result = $this->withSession($_SESSION)->get('/dashboard');

        $result->assertOK();
        $result->assertSee('Luca Marin');
        $result->assertDontSee('Maria Enache');
        $result->assertDontSee('Toti antrenorii');
    }

    public function testParentCannotAccessDashboard(): void
    {
        $parent = $this->findUserByEmail('cristina@academia.local');

        $this->actingAs($parent);
        $result = $this->withSession($_SESSION)->get('/dashboard');

        $result->assertStatus(403);
    }

    private function findUserByEmail(string $email)
    {
        return model(UserModel::class)->findByCredentials(['email' => $email]);
    }
}
