<?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 AttendanceFeatureTest 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 testCoachCanCreateSessionAndSaveCheckInForOwnGroup(): void
    {
        $coach   = $this->findUserByEmail('andrei@academia.local');
        $groupId = (int) db_connect()->table('academy_groups')->select('id')->where('name', 'Delfinas Initiere')->get()->getRowArray()['id'];

        $this->actingAs($coach);

        $create = $this->withSession($_SESSION)->post('/attendance', [
            'academy_group_id' => (string) $groupId,
            'coach_id' => '',
            'session_date' => '2026-04-21',
            'start_time' => '17:00',
            'end_time' => '18:30',
            'status' => 'scheduled',
            'notes' => 'Sesiune creata din feature test.',
        ]);

        $create->assertRedirect();

        $session = db_connect()
            ->table('attendance_sessions')
            ->where('academy_group_id', $groupId)
            ->where('session_date', '2026-04-21')
            ->orderBy('id', 'DESC')
            ->get()
            ->getRowArray();

        $this->assertNotNull($session);

        $show = $this->withSession($_SESSION)->get('/attendance/' . $session['id']);
        $show->assertOK();
        $show->assertSee('Delfinas Initiere');

        $children = db_connect()
            ->table('children')
            ->select('id, full_name')
            ->where('academy_group_id', $groupId)
            ->where('status !=', 'left')
            ->orderBy('full_name', 'ASC')
            ->get()
            ->getResultArray();

        $records = [];
        foreach ($children as $child) {
            $records[(int) $child['id']] = [
                'status' => $child['full_name'] === 'Sofia Radu' ? 'absent_excused' : 'present',
                'notes' => $child['full_name'] === 'Sofia Radu' ? 'Parinte anunta indisponibilitate.' : '',
            ];
        }

        $checkIn = $this->withSession($_SESSION)->post('/attendance/' . $session['id'] . '/check-in', [
            'records' => $records,
        ]);

        $checkIn->assertRedirect();
        $this->seeInDatabase('attendance_records', [
            'attendance_session_id' => $session['id'],
            'status' => 'absent_excused',
        ]);
        $this->seeInDatabase('attendance_sessions', [
            'id' => $session['id'],
            'status' => 'completed',
        ]);
    }

    public function testCoachCannotAccessForeignSession(): void
    {
        $coach     = $this->findUserByEmail('andrei@academia.local');
        $sessionId = (int) db_connect()
            ->table('attendance_sessions sessions')
            ->select('sessions.id')
            ->join('academy_groups groups', 'groups.id = sessions.academy_group_id')
            ->where('groups.name', 'Performanta Bazin')
            ->orderBy('sessions.id', 'DESC')
            ->get()
            ->getRowArray()['id'];

        $this->actingAs($coach);

        $show = $this->withSession($_SESSION)->get('/attendance/' . $sessionId);
        $show->assertStatus(403);
    }

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