<?php

declare(strict_types=1);

namespace App\Tests\Functional\Controller\Mail;

use App\Module\Core\Domain\Entity\User;
use App\Module\Mail\Domain\Entity\MailFolder;
use App\Module\Mail\Domain\Entity\MailMessage;
use App\Module\ProjectManagement\Domain\Entity\Project;
use App\Module\ProjectManagement\Domain\Entity\Task;
use DateTimeImmutable;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

/**
 * @internal
 */
class MailTaskIntegrationControllerTest extends WebTestCase
{
    public function testLinkTaskReturns401WhenNotAuthenticated(): void
    {
        $client = static::createClient();
        $client->request('POST', '/api/mail/messages/1/link-task', [], [], ['CONTENT_TYPE' => 'application/json'], json_encode(['taskId' => 1]));

        self::assertResponseStatusCodeSame(401);
    }

    public function testUnlinkTaskReturns401WhenNotAuthenticated(): void
    {
        $client = static::createClient();
        $client->request('DELETE', '/api/mail/messages/1/link-task/1');

        self::assertResponseStatusCodeSame(401);
    }

    public function testTaskMailsListReturns401WhenNotAuthenticated(): void
    {
        $client = static::createClient();
        $client->request('GET', '/api/tasks/1/mails');

        self::assertResponseStatusCodeSame(401);
    }

    public function testCreateTaskReturns401WhenNotAuthenticated(): void
    {
        $client = static::createClient();
        $client->request('POST', '/api/mail/messages/1/create-task', [], [], ['CONTENT_TYPE' => 'application/json'], json_encode(['projectId' => 1]));

        self::assertResponseStatusCodeSame(401);
    }

    public function testCreateTaskAppliesStatusAndAssigneeAndIgnoresPriority(): void
    {
        $client    = static::createClient();
        $container = static::getContainer();
        $em        = $container->get('doctrine.orm.entity_manager');

        $admin = $em->getRepository(User::class)->findOneBy(['username' => 'admin']);
        $client->loginUser($admin);

        $project = $em->getRepository(Project::class)->findOneBy([]);
        self::assertNotNull($project);
        $status = $project->getWorkflow()->getStatuses()->first();
        self::assertNotFalse($status);

        // Create a mail folder + message in the test DB (none in fixtures)
        $folder = new MailFolder();
        $folder->setDisplayName('Boîte de réception');
        $folder->setUnreadCount(0);
        $folder->setTotalCount(0);
        $em->persist($folder);

        $rand = random_int(100000, 999999);
        $folder->setPath('INBOX.'.$rand);

        $message = new MailMessage();
        $message->setMessageId('test-'.$rand.'@example.com');
        $message->setFolder($folder);
        $message->setUid($rand);
        $message->setFromAddress('sender@example.com');
        $message->setToAddresses([]);
        $message->setSentAt(new DateTimeImmutable());
        $message->setIsRead(false);
        $message->setIsFlagged(false);
        $message->setHasAttachments(false);
        $message->setSyncedAt(new DateTimeImmutable());
        $message->setSubject('Sujet de test');
        $em->persist($message);
        $em->flush();

        $client->request(
            'POST',
            '/api/mail/messages/'.$message->getId().'/create-task',
            [],
            [],
            ['CONTENT_TYPE' => 'application/json'],
            json_encode([
                'projectId'  => $project->getId(),
                'assigneeId' => $admin->getId(),
                'statusId'   => $status->getId(),
                'priorityId' => 999, // doit être ignoré
            ])
        );

        self::assertResponseStatusCodeSame(201);
        $payload = json_decode($client->getResponse()->getContent(), true);

        $em->clear();
        $task = $em->getRepository(Task::class)->find($payload['taskId']);
        self::assertSame($status->getId(), $task->getStatus()?->getId());
        self::assertSame($admin->getId(), $task->getAssignee()?->getId());
        self::assertNull($task->getPriority());
    }
}
