<?php

namespace App\Tests\Controller;

use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class HomeControllerTest extends WebTestCase
{
    public function testIndexReturnsSuccess(): void
    {
        $client = static::createClient();
        $client->request('GET', '/');

        self::assertResponseIsSuccessful();
    }

    public function testTarifsReturnsSuccess(): void
    {
        $client = static::createClient();
        $client->request('GET', '/tarifs');

        self::assertResponseIsSuccessful();
    }

    public function testOrganizersReturnsSuccess(): void
    {
        $client = static::createClient();
        $client->request('GET', '/organisateurs');

        self::assertResponseIsSuccessful();
    }

    public function testOrganizerDetailReturnsSuccess(): void
    {
        $client = static::createClient();
        $em = static::getContainer()->get(EntityManagerInterface::class);

        $organizer = $em->getRepository(User::class)->findOneBy([]);
        $found = false;
        if ($organizer) {
            foreach ($em->getRepository(User::class)->findAll() as $user) {
                if (\in_array('ROLE_ORGANIZER', $user->getRoles(), true) && $user->isApproved()) {
                    $organizer = $user;
                    $found = true;
                    break;
                }
            }
        }

        if (!$found) {
            $organizer = new User();
            $organizer->setEmail('test-orga-detail@example.com');
            $organizer->setFirstName('Test');
            $organizer->setLastName('Orga');
            $organizer->setPassword('hashed');
            $organizer->setRoles(['ROLE_ORGANIZER']);
            $organizer->setIsApproved(true);
            $organizer->setIsVerified(true);
            $organizer->setCompanyName('Asso Test');
            $organizer->setSiret('12345678901234');
            $em->persist($organizer);
            $em->flush();
        }

        $client->request('GET', '/organisateur/'.$organizer->getId().'-'.$organizer->getSlug());
        self::assertResponseIsSuccessful();
        self::assertSelectorTextContains('h1', $organizer->getCompanyName() ?? $organizer->getFirstName());
    }

    public function testOrganizerDetailRedirectsOnWrongSlug(): void
    {
        $client = static::createClient();
        $em = static::getContainer()->get(EntityManagerInterface::class);

        $organizer = new User();
        $organizer->setEmail('test-orga-slug-'.uniqid().'@example.com');
        $organizer->setFirstName('Slug');
        $organizer->setLastName('Test');
        $organizer->setPassword('hashed');
        $organizer->setRoles(['ROLE_ORGANIZER']);
        $organizer->setIsApproved(true);
        $organizer->setIsVerified(true);
        $organizer->setCompanyName('Mon Asso');
        $em->persist($organizer);
        $em->flush();

        $client->request('GET', '/organisateur/'.$organizer->getId().'-mauvais-slug');
        self::assertResponseRedirects('/organisateur/'.$organizer->getId().'-mon-asso', 301);
    }

    public function testOrganizerDetailNotFoundReturns404(): void
    {
        $client = static::createClient();
        $client->request('GET', '/organisateur/999999-inexistant');

        self::assertResponseStatusCodeSame(404);
    }

    public function testOrganizerDetailNonApprovedReturns404(): void
    {
        $client = static::createClient();
        $em = static::getContainer()->get(EntityManagerInterface::class);

        $organizer = new User();
        $organizer->setEmail('test-orga-noapprove-'.uniqid().'@example.com');
        $organizer->setFirstName('Test');
        $organizer->setLastName('NonApproved');
        $organizer->setPassword('hashed');
        $organizer->setRoles(['ROLE_ORGANIZER']);
        $organizer->setIsApproved(false);
        $organizer->setIsVerified(true);
        $em->persist($organizer);
        $em->flush();

        $client->request('GET', '/organisateur/'.$organizer->getId().'-'.$organizer->getSlug());
        self::assertResponseStatusCodeSame(404);
    }

    public function testOrganizerDetailBuyerReturns404(): void
    {
        $client = static::createClient();
        $em = static::getContainer()->get(EntityManagerInterface::class);

        $buyer = new User();
        $buyer->setEmail('test-buyer-detail-'.uniqid().'@example.com');
        $buyer->setFirstName('Buyer');
        $buyer->setLastName('Test');
        $buyer->setPassword('hashed');
        $buyer->setRoles(['ROLE_USER']);
        $buyer->setIsVerified(true);
        $em->persist($buyer);
        $em->flush();

        $client->request('GET', '/organisateur/'.$buyer->getId().'-'.$buyer->getSlug());
        self::assertResponseStatusCodeSame(404);
    }

    public function testEventsPageReturnsSuccess(): void
    {
        $client = static::createClient();
        $client->request('GET', '/evenements');

        self::assertResponseIsSuccessful();
    }

    public function testEventsPageWithSearch(): void
    {
        $client = static::createClient();
        $client->request('GET', '/evenements?q=brocante');

        self::assertResponseIsSuccessful();
    }

    public function testEventsPageWithCityFilter(): void
    {
        $client = static::createClient();
        $client->request('GET', '/evenements?city=Paris');

        self::assertResponseIsSuccessful();
    }

    public function testEventsPageWithDateFilter(): void
    {
        $client = static::createClient();
        $client->request('GET', '/evenements?date=2026-08-01');

        self::assertResponseIsSuccessful();
    }

    public function testEventsPageWithAllFilters(): void
    {
        $client = static::createClient();
        $client->request('GET', '/evenements?q=test&city=Paris&date=2026-08-01');

        self::assertResponseIsSuccessful();
    }

    public function testEventsPageWithSearchAndCityMatchingResults(): void
    {
        $client = static::createClient();
        $em = static::getContainer()->get(EntityManagerInterface::class);

        $user = new User();
        $user->setEmail('test-events-search-'.uniqid().'@example.com');
        $user->setFirstName('Search');
        $user->setLastName('Test');
        $user->setPassword('hashed');
        $user->setRoles(['ROLE_ORGANIZER']);
        $user->setIsApproved(true);
        $user->setIsVerified(true);
        $em->persist($user);

        $event = new \App\Entity\Event();
        $event->setAccount($user);
        $event->setTitle('Brocante Geante');
        $event->setStartAt(new \DateTimeImmutable('2026-08-01 10:00'));
        $event->setEndAt(new \DateTimeImmutable('2026-08-01 18:00'));
        $event->setAddress('1 rue');
        $event->setZipcode('75001');
        $event->setCity('Paris');
        $event->setIsOnline(true);
        $em->persist($event);
        $em->flush();

        // Mock EventIndexService to return the event (simulates Meilisearch match)
        $eventIndex = $this->createMock(\App\Service\EventIndexService::class);
        $eventIndex->method('searchEvents')->willReturn([$event]);
        static::getContainer()->set(\App\Service\EventIndexService::class, $eventIndex);

        $client->request('GET', '/evenements?q=Brocante&city=Paris');

        self::assertResponseIsSuccessful();
    }

    public function testEventStockRoute(): void
    {
        $client = static::createClient();
        $em = static::getContainer()->get(EntityManagerInterface::class);

        $user = new User();
        $user->setEmail('test-stock-'.uniqid().'@example.com');
        $user->setFirstName('Stock');
        $user->setLastName('Test');
        $user->setPassword('hashed');
        $user->setRoles(['ROLE_ORGANIZER']);
        $user->setIsApproved(true);
        $user->setIsVerified(true);
        $em->persist($user);

        $event = new \App\Entity\Event();
        $event->setAccount($user);
        $event->setTitle('Stock Event');
        $event->setStartAt(new \DateTimeImmutable('2026-08-01 10:00'));
        $event->setEndAt(new \DateTimeImmutable('2026-08-01 18:00'));
        $event->setAddress('1 rue');
        $event->setZipcode('75001');
        $event->setCity('Paris');
        $event->setIsOnline(true);
        $em->persist($event);

        $category = new \App\Entity\Category();
        $category->setName('Cat Stock');
        $category->setEvent($event);
        $em->persist($category);

        $billet = new \App\Entity\Billet();
        $billet->setName('Entree');
        $billet->setCategory($category);
        $billet->setPriceHT(1000);
        $billet->setQuantity(50);
        $em->persist($billet);
        $em->flush();

        $client->request('GET', '/evenement/'.$event->getId().'/stock');
        self::assertResponseIsSuccessful();

        $data = json_decode($client->getResponse()->getContent(), true);
        self::assertSame(50, $data[$billet->getId()]);
    }

    public function testEventStockNotFound(): void
    {
        $client = static::createClient();
        $client->request('GET', '/evenement/999999/stock');

        self::assertResponseIsSuccessful();
        self::assertSame('[]', $client->getResponse()->getContent());
    }

    public function testEventDetailNotFoundReturns404(): void
    {
        $client = static::createClient();
        $client->request('GET', '/evenement/orga/999999-test');

        self::assertResponseStatusCodeSame(404);
    }

    public function testEventDetailReturnsSuccess(): void
    {
        $client = static::createClient();
        $em = static::getContainer()->get(EntityManagerInterface::class);

        $user = new User();
        $user->setEmail('test-event-orga-'.uniqid().'@example.com');
        $user->setFirstName('Orga');
        $user->setLastName('Event');
        $user->setPassword('hashed');
        $user->setRoles(['ROLE_ORGANIZER']);
        $user->setIsApproved(true);
        $user->setIsVerified(true);
        $user->setCompanyName('Asso Event');
        $em->persist($user);

        $event = new \App\Entity\Event();
        $event->setAccount($user);
        $event->setTitle('Test Event');
        $event->setStartAt(new \DateTimeImmutable('2026-08-01 10:00'));
        $event->setEndAt(new \DateTimeImmutable('2026-08-01 18:00'));
        $event->setAddress('1 rue test');
        $event->setZipcode('75001');
        $event->setCity('Paris');
        $event->setIsOnline(true);
        $em->persist($event);
        $em->flush();

        $client->request('GET', '/evenement/'.$user->getSlug().'/'.$event->getId().'-'.$event->getSlug());
        self::assertResponseIsSuccessful();
    }

    public function testEventDetailWithCategoriesAndBillets(): void
    {
        $client = static::createClient();
        $em = static::getContainer()->get(EntityManagerInterface::class);

        $user = new User();
        $user->setEmail('test-event-billets-'.uniqid().'@example.com');
        $user->setFirstName('Orga');
        $user->setLastName('Billets');
        $user->setPassword('hashed');
        $user->setRoles(['ROLE_ORGANIZER']);
        $user->setIsApproved(true);
        $user->setIsVerified(true);
        $user->setCompanyName('Asso Billets');
        $em->persist($user);

        $event = new \App\Entity\Event();
        $event->setAccount($user);
        $event->setTitle('Event Billets Test');
        $event->setStartAt(new \DateTimeImmutable('2026-08-01 10:00'));
        $event->setEndAt(new \DateTimeImmutable('2026-08-01 18:00'));
        $event->setAddress('1 rue test');
        $event->setZipcode('75001');
        $event->setCity('Paris');
        $event->setIsOnline(true);
        $em->persist($event);

        $category = new \App\Entity\Category();
        $category->setName('Cat Active');
        $category->setEvent($event);
        $category->setStartAt(new \DateTimeImmutable('-1 day'));
        $category->setEndAt(new \DateTimeImmutable('+30 days'));
        $em->persist($category);

        $billet = new \App\Entity\Billet();
        $billet->setName('Entree');
        $billet->setCategory($category);
        $billet->setPriceHT(1500);
        $em->persist($billet);

        $billetNotBuyable = new \App\Entity\Billet();
        $billetNotBuyable->setName('Non Achetable');
        $billetNotBuyable->setCategory($category);
        $billetNotBuyable->setPriceHT(0);
        $billetNotBuyable->setNotBuyable(true);
        $em->persist($billetNotBuyable);

        $categoryHidden = new \App\Entity\Category();
        $categoryHidden->setName('Cat Hidden');
        $categoryHidden->setEvent($event);
        $categoryHidden->setIsHidden(true);
        $em->persist($categoryHidden);

        $categoryInactive = new \App\Entity\Category();
        $categoryInactive->setName('Cat Inactive');
        $categoryInactive->setEvent($event);
        $categoryInactive->setStartAt(new \DateTimeImmutable('+10 days'));
        $categoryInactive->setEndAt(new \DateTimeImmutable('+20 days'));
        $em->persist($categoryInactive);

        $em->flush();

        $client->request('GET', '/evenement/'.$user->getSlug().'/'.$event->getId().'-'.$event->getSlug());
        self::assertResponseIsSuccessful();
    }

    public function testEventDetailRedirectsOnWrongSlug(): void
    {
        $client = static::createClient();
        $em = static::getContainer()->get(EntityManagerInterface::class);

        $user = new User();
        $user->setEmail('test-event-slug-'.uniqid().'@example.com');
        $user->setFirstName('Slug');
        $user->setLastName('Test');
        $user->setPassword('hashed');
        $user->setRoles(['ROLE_ORGANIZER']);
        $user->setIsApproved(true);
        $user->setIsVerified(true);
        $user->setCompanyName('Slug Asso');
        $em->persist($user);

        $event = new \App\Entity\Event();
        $event->setAccount($user);
        $event->setTitle('Slug Event');
        $event->setStartAt(new \DateTimeImmutable('2026-08-01 10:00'));
        $event->setEndAt(new \DateTimeImmutable('2026-08-01 18:00'));
        $event->setAddress('1 rue');
        $event->setZipcode('75001');
        $event->setCity('Paris');
        $event->setIsOnline(true);
        $em->persist($event);
        $em->flush();

        $client->request('GET', '/evenement/'.$user->getSlug().'/'.$event->getId().'-mauvais-slug');
        self::assertResponseRedirects();
    }

    public function testEventDetailOfflineReturns404(): void
    {
        $client = static::createClient();
        $em = static::getContainer()->get(EntityManagerInterface::class);

        $user = new User();
        $user->setEmail('test-event-offline-'.uniqid().'@example.com');
        $user->setFirstName('Offline');
        $user->setLastName('Test');
        $user->setPassword('hashed');
        $user->setRoles(['ROLE_ORGANIZER']);
        $user->setIsApproved(true);
        $user->setIsVerified(true);
        $em->persist($user);

        $event = new \App\Entity\Event();
        $event->setAccount($user);
        $event->setTitle('Offline Event');
        $event->setStartAt(new \DateTimeImmutable('2026-08-01 10:00'));
        $event->setEndAt(new \DateTimeImmutable('2026-08-01 18:00'));
        $event->setAddress('1 rue');
        $event->setZipcode('75001');
        $event->setCity('Paris');
        $event->setIsOnline(false);
        $em->persist($event);
        $em->flush();

        $client->request('GET', '/evenement/'.$user->getSlug().'/'.$event->getId().'-'.$event->getSlug());
        self::assertResponseStatusCodeSame(404);
    }

    public function testOfflinePageReturnsSuccess(): void
    {
        $client = static::createClient();
        $client->request('GET', '/offline');

        self::assertResponseIsSuccessful();
    }

    public function testEventContactEmptyFieldsRedirects(): void
    {
        $client = static::createClient();
        $em = static::getContainer()->get(EntityManagerInterface::class);

        $user = new User();
        $user->setEmail('test-contact-orga-'.uniqid().'@example.com');
        $user->setFirstName('Contact');
        $user->setLastName('Orga');
        $user->setPassword('hashed');
        $user->setRoles(['ROLE_ORGANIZER']);
        $user->setIsApproved(true);
        $user->setIsVerified(true);
        $em->persist($user);

        $event = new \App\Entity\Event();
        $event->setAccount($user);
        $event->setTitle('Contact Event');
        $event->setStartAt(new \DateTimeImmutable('2026-08-01 10:00'));
        $event->setEndAt(new \DateTimeImmutable('2026-08-01 18:00'));
        $event->setAddress('1 rue');
        $event->setZipcode('75001');
        $event->setCity('Paris');
        $event->setIsOnline(true);
        $em->persist($event);
        $em->flush();

        $client->request('POST', '/evenement/'.$event->getId().'/contact', [
            'name' => '',
            'firstname' => '',
            'email' => '',
            'message' => '',
        ]);

        self::assertResponseRedirects();
    }

    public function testEventDetailRedirectsOnWrongOrgaSlug(): void
    {
        $client = static::createClient();
        $em = static::getContainer()->get(EntityManagerInterface::class);

        $user = new User();
        $user->setEmail('test-orga-slug2-'.uniqid().'@example.com');
        $user->setFirstName('Wrong');
        $user->setLastName('Orga');
        $user->setPassword('hashed');
        $user->setRoles(['ROLE_ORGANIZER']);
        $user->setIsApproved(true);
        $user->setIsVerified(true);
        $user->setCompanyName('Real Asso');
        $em->persist($user);

        $event = new \App\Entity\Event();
        $event->setAccount($user);
        $event->setTitle('Orga Slug Test');
        $event->setStartAt(new \DateTimeImmutable('2026-08-01 10:00'));
        $event->setEndAt(new \DateTimeImmutable('2026-08-01 18:00'));
        $event->setAddress('1 rue');
        $event->setZipcode('75001');
        $event->setCity('Paris');
        $event->setIsOnline(true);
        $em->persist($event);
        $em->flush();

        $client->request('GET', '/evenement/wrong-slug/'.$event->getId().'-'.$event->getSlug());
        self::assertResponseRedirects();
    }

    public function testEventContactNotFoundReturns404(): void
    {
        $client = static::createClient();
        $client->request('POST', '/evenement/999999/contact', [
            'name' => 'Test',
            'firstname' => 'Test',
            'email' => 'test@example.com',
            'message' => 'Hello',
        ]);

        self::assertResponseStatusCodeSame(404);
    }

    public function testEventContactSuccess(): void
    {
        $client = static::createClient();
        $em = static::getContainer()->get(EntityManagerInterface::class);

        $mailer = $this->createMock(\App\Service\MailerService::class);
        $mailer->expects(self::once())->method('sendEmail');
        static::getContainer()->set(\App\Service\MailerService::class, $mailer);

        $user = new User();
        $user->setEmail('test-contact-success-'.uniqid().'@example.com');
        $user->setFirstName('Contact');
        $user->setLastName('Success');
        $user->setPassword('hashed');
        $user->setRoles(['ROLE_ORGANIZER']);
        $user->setIsApproved(true);
        $user->setIsVerified(true);
        $em->persist($user);

        $event = new \App\Entity\Event();
        $event->setAccount($user);
        $event->setTitle('Contact Success Event');
        $event->setStartAt(new \DateTimeImmutable('2026-08-01 10:00'));
        $event->setEndAt(new \DateTimeImmutable('2026-08-01 18:00'));
        $event->setAddress('1 rue');
        $event->setZipcode('75001');
        $event->setCity('Paris');
        $event->setIsOnline(true);
        $em->persist($event);
        $em->flush();

        $client->request('POST', '/evenement/'.$event->getId().'/contact', [
            'name' => 'Dupont',
            'firstname' => 'Jean',
            'email' => 'jean@example.com',
            'message' => 'Question sur votre evenement',
        ]);

        self::assertResponseRedirects();
    }
}
