<?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 AlertsFeatureTest 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 testCoachAlertsAreScopedAndNotificationCanBeMarkedRead(): void
    {
        $coach          = $this->findUserByEmail('andrei@academia.local');
        $notificationId = (int) db_connect()
            ->table('notifications')
            ->select('id')
            ->where('title', 'Ready in grupa ta')
            ->get()
            ->getRowArray()['id'];

        $this->actingAs($coach);

        $index = $this->withSession($_SESSION)->get('/alerts');

        $index->assertOK();
        $index->assertSee('Luca Marin');
        $index->assertDontSee('Maria Enache');
        $index->assertSee('Ready in grupa ta');

        $markRead = $this->withSession($_SESSION)->post('/alerts/notifications/' . $notificationId . '/read');
        $markRead->assertRedirect();

        $this->seeInDatabase('notifications', [
            'id' => $notificationId,
            'status' => 'read',
        ]);
    }

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