<?php

use App\Database\Seeds\DatabaseSeeder;
use App\Models\CoachModel;
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 CoachesFeatureTest 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 testCoachCannotAccessAdminOnlyCreateForms(): void
    {
        $coach = $this->findUserByEmail('andrei@academia.local');

        $this->actingAs($coach);

        foreach (['/children/new', '/coaches/new', '/groups/new', '/levels/new'] as $path) {
            $result = $this->withSession($_SESSION)->get($path);
            $result->assertStatus(403);
        }
    }

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

        $this->actingAs($admin);

        $response = $this->withSession($_SESSION)->post('/coaches', [
            'full_name' => 'Test Coach',
            'display_role' => 'Coach',
            'phone' => '0712 345 678',
            'email' => 'test.coach@example.test',
            'avatar_path' => 'uploads/coaches/test-coach.png',
            'is_active' => '1',
            'notes' => 'Creat prin feature test.',
            'username' => 'test.coach',
            'password' => 'Academia123!',
            'password_confirmation' => 'Academia123!',
            'availability' => [
                1 => ['enabled' => '1', 'start' => '16:00', 'end' => '19:00'],
                3 => ['enabled' => '1', 'start' => '17:00', 'end' => '20:00'],
            ],
        ]);

        $response->assertRedirect();
        $this->seeInDatabase('coaches', ['full_name' => 'Test Coach', 'email' => 'test.coach@example.test']);

        $createdCoach = model(CoachModel::class)->where('email', 'test.coach@example.test')->first();

        $this->assertNotNull($createdCoach);
        $this->seeInDatabase('users', [
            'id' => $createdCoach['user_id'],
            'username' => 'test.coach',
        ]);
        $this->seeInDatabase('coach_availability', [
            'coach_id' => $createdCoach['id'],
            'day_of_week' => 1,
        ]);

        $profile = $this->withSession($_SESSION)->get('/coaches/' . $createdCoach['id']);

        $profile->assertOK();
        $profile->assertSee('Test Coach');
        $profile->assertSee('uploads/coaches/test-coach.png');
    }

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