<?php
declare(strict_types=1);

namespace App\Test\TestCase\Controller\Admin;

use Cake\ORM\TableRegistry;
use Cake\TestSuite\IntegrationTestTrait;
use Cake\TestSuite\TestCase;

class SessionControllerTest extends TestCase
{
    use IntegrationTestTrait;

    protected function setUp(): void
    {
        parent::setUp();

        $adminUsers = TableRegistry::getTableLocator()->get('AdminUsers');
        $adminUser = $adminUsers->find()->where(['email' => 'admin@candlecraft.local'])->first();

        if ($adminUser === null) {
            $adminUser = $adminUsers->newEntity([
                'email' => 'admin@candlecraft.local',
                'password_hash' => password_hash('CandlecraftDemo!23', PASSWORD_DEFAULT),
                'display_name' => 'CandleCraft Owner',
                'is_active' => true,
            ]);
            $adminUsers->saveOrFail($adminUser);
        }
    }

    public function testLoginPageRenders(): void
    {
        $this->get('/admin/login');

        $this->assertResponseOk();
        $this->assertResponseContains('Sign in to the inbox');
    }

    public function testLoginSucceedsWithValidCredentials(): void
    {
        $this->enableCsrfToken();
        $this->enableSecurityToken();

        $this->post('/admin/login', [
            'email' => 'admin@candlecraft.local',
            'password' => 'CandlecraftDemo!23',
        ]);

        $this->assertRedirectContains('/admin/messages');
        $this->assertSession('admin@candlecraft.local', 'Auth.Admin.email');
    }

    public function testLoginFailsWithInvalidCredentials(): void
    {
        $this->enableCsrfToken();
        $this->enableSecurityToken();

        $this->post('/admin/login', [
            'email' => 'admin@candlecraft.local',
            'password' => 'wrong-password',
        ]);

        $this->assertResponseOk();
        $this->assertResponseContains('Invalid email or password.');
    }
}
