<?php
declare(strict_types=1);

namespace App\Test\TestCase\Controller\Admin;

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

class ContactMessagesControllerTest extends TestCase
{
    use IntegrationTestTrait;

    private int $adminId;

    private int $messageId;

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

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

        if ($adminUser === null) {
            $adminUser = $adminUsers->newEntity([
                'email' => 'admin.test@example.com',
                'password_hash' => password_hash('CandlecraftDemo!23', PASSWORD_DEFAULT),
                'display_name' => 'CandleCraft Owner',
                'is_active' => true,
            ]);
            $adminUsers->saveOrFail($adminUser);
        }
        $this->adminId = (int)$adminUser->id;

        $messages = TableRegistry::getTableLocator()->get('ContactMessages');
        $message = $messages->find()->where(['email' => 'maya.test@example.com'])->first();

        if ($message === null) {
            $message = $messages->newEntity([
                'full_name' => 'Maya Chen',
                'email' => 'maya.test@example.com',
                'phone' => '0412000111',
                'interest_area' => 'pottery',
                'subject' => 'Trying pottery for the first time',
                'message_body' => 'I am looking for beginner-friendly pottery tutoring and would like to know how the first lesson works.',
                'status' => 'new',
                'consent_to_contact' => true,
            ]);
            $messages->saveOrFail($message);
        }
        $this->messageId = (int)$message->id;
    }

    /**
     * @return array<string, array<string, int|string>>
     */
    private function adminSession(): array
    {
        return [
            'Auth.Admin' => [
                'id' => $this->adminId,
                'email' => 'admin.test@example.com',
                'display_name' => 'CandleCraft Owner',
            ],
        ];
    }

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

        $this->assertRedirectContains('/admin/login');
    }

    public function testIndexShowsMessagesForLoggedInAdmin(): void
    {
        $this->session($this->adminSession());
        $this->get('/admin/messages');

        $this->assertResponseOk();
        $this->assertResponseContains("Today's enquiries");
        $this->assertResponseContains('Maya Chen');
    }

    public function testViewUpdatesStatusAndNotes(): void
    {
        $messages = TableRegistry::getTableLocator()->get('ContactMessages');

        $this->session($this->adminSession());
        $this->enableCsrfToken();
        $this->enableSecurityToken();

        $this->post('/admin/messages/' . $this->messageId, [
            'status' => 'resolved',
            'admin_notes' => 'Followed up by phone and shared beginner pottery details.',
        ]);

        $this->assertRedirectContains('/admin/messages/' . $this->messageId);

        $updatedMessage = $messages->get($this->messageId);
        $this->assertSame('resolved', $updatedMessage->status);
        $this->assertSame('Followed up by phone and shared beginner pottery details.', $updatedMessage->admin_notes);
        $this->assertSame($this->adminId, $updatedMessage->reviewed_by_admin_user_id);
    }
}
