<?php

namespace App\Tests\Controller\Admin;

use App\Controller\Admin\ClientsController;
use App\Controller\Admin\DashboardController;
use App\Controller\Admin\FacturationController;
use App\Controller\Admin\MembresController;
use App\Controller\Admin\ProfilController;
use App\Controller\Admin\RevendeursController;
use App\Controller\Admin\ServicesController;
use App\Controller\Admin\StatsController;
use App\Controller\Admin\StatusController;
use App\Controller\Admin\SyncController;
use App\Entity\ServiceMessage;
use App\Repository\CustomerRepository;
use App\Repository\PriceAutomaticRepository;
use App\Repository\RevendeurRepository;
use App\Repository\ServiceCategoryRepository;
use App\Repository\ServiceRepository;
use App\Repository\StripeWebhookSecretRepository;
use App\Repository\UserRepository;
use App\Service\KeycloakAdminService;
use App\Service\MeilisearchService;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Twig\Environment;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;

class AdminControllersTest extends TestCase
{
    private function createMockController(string $class, array $constructorArgs = []): mixed
    {
        $twig = $this->createStub(Environment::class);
        $twig->method('render')->willReturn('<html></html>');

        $container = $this->createStub(ContainerInterface::class);
        $container->method('has')->willReturnMap([
            ['twig', true],
            ['parameter_bag', true],
        ]);
        $container->method('get')->willReturnMap([
            ['twig', $twig],
        ]);

        $controller = new $class(...$constructorArgs);
        $controller->setContainer($container);

        return $controller;
    }

    public function testDashboardIndex(): void
    {
        $controller = $this->createMockController(DashboardController::class);
        $response = $controller->index();
        $this->assertInstanceOf(Response::class, $response);
    }

    public function testServicesIndex(): void
    {
        $controller = $this->createMockController(ServicesController::class);
        $response = $controller->index();
        $this->assertInstanceOf(Response::class, $response);
    }

    public function testClientsIndex(): void
    {
        $repo = $this->createStub(CustomerRepository::class);
        $repo->method('findBy')->willReturn([]);
        $em = $this->createStub(\Doctrine\ORM\EntityManagerInterface::class);
        $controller = $this->createMockController(ClientsController::class);
        $response = $controller->index($repo, $em);
        $this->assertInstanceOf(Response::class, $response);
    }

    public function testFacturationIndex(): void
    {
        $controller = $this->createMockController(FacturationController::class);
        $response = $controller->index();
        $this->assertInstanceOf(Response::class, $response);
    }

    public function testRevendeursIndex(): void
    {
        $logger = $this->createStub(LoggerInterface::class);
        $repo = $this->createStub(RevendeurRepository::class);
        $repo->method('findBy')->willReturn([]);
        
        $controller = $this->createMockController(RevendeursController::class, [$logger]);
        $response = $controller->index($repo);
        $this->assertInstanceOf(Response::class, $response);
    }

    public function testMembresIndex(): void
    {
        $logger = $this->createStub(LoggerInterface::class);
        $keycloak = $this->createStub(KeycloakAdminService::class);
        $keycloak->method('listUsers')->willReturn([]);
        $userRepo = $this->createStub(UserRepository::class);
        
        $controller = $this->createMockController(MembresController::class, [$logger]);
        $response = $controller->index($keycloak, $userRepo);
        $this->assertInstanceOf(Response::class, $response);
    }

    public function testStatsIndex(): void
    {
        $stubEm = $this->createStub(\Doctrine\ORM\EntityManagerInterface::class);
        $query = $this->getMockBuilder(\Doctrine\ORM\Query::class)
            ->setConstructorArgs([$stubEm])
            ->onlyMethods(['getResult', '_doExecute', 'getSQL'])
            ->getMock();
        $query->method('getResult')->willReturn([]);
        $qb = $this->createStub(\Doctrine\ORM\QueryBuilder::class);
        $qb->method('select')->willReturnSelf();
        $qb->method('from')->willReturnSelf();
        $qb->method('where')->willReturnSelf();
        $qb->method('andWhere')->willReturnSelf();
        $qb->method('setParameter')->willReturnSelf();
        $qb->method('getQuery')->willReturn($query);
        $em = $this->createStub(\Doctrine\ORM\EntityManagerInterface::class);
        $em->method('createQueryBuilder')->willReturn($qb);
        $controller = $this->createMockController(StatsController::class, [$em]);
        $request = new Request();
        $response = $controller->index($request);
        $this->assertInstanceOf(Response::class, $response);
    }

    public function testStatusIndex(): void
    {
        $catRepo = $this->createStub(ServiceCategoryRepository::class);
        $catRepo->method('findBy')->willReturn([]);
        $svcRepo = $this->createStub(ServiceRepository::class);
        $svcRepo->method('findBy')->willReturn([]);
        
        $em = $this->createStub(EntityManagerInterface::class);
        $msgRepo = $this->createStub(EntityRepository::class);
        $msgRepo->method('findBy')->willReturn([]);

        $em->method('getRepository')->willReturn($msgRepo);

        $controller = $this->createMockController(StatusController::class);
        $response = $controller->index($catRepo, $svcRepo, $em);
        $this->assertInstanceOf(Response::class, $response);
    }

    public function testSyncIndex(): void
    {
        $crepo = $this->createStub(CustomerRepository::class);
        $rrepo = $this->createStub(RevendeurRepository::class);
        $prepo = $this->createStub(PriceAutomaticRepository::class);
        $srepo = $this->createStub(StripeWebhookSecretRepository::class);
        $srepo->method('findAll')->willReturn([]);
        $contactRepo = $this->createStub(\Doctrine\ORM\EntityRepository::class);
        $contactRepo->method('count')->willReturn(0);
        $em = $this->createStub(\Doctrine\ORM\EntityManagerInterface::class);
        $em->method('getRepository')->willReturn($contactRepo);
        $meilisearch = $this->createStub(\App\Service\MeilisearchService::class);
        $controller = $this->createMockController(SyncController::class);
        $response = $controller->index($crepo, $rrepo, $prepo, $srepo, $em, $meilisearch);
        $this->assertInstanceOf(Response::class, $response);
    }

    public function testProfilIndex(): void
    {
        $logger = $this->createStub(LoggerInterface::class);
        $controller = $this->createMockController(ProfilController::class, [$logger]);
        $response = $controller->index();
        $this->assertInstanceOf(Response::class, $response);
    }

    // ---------------------------------------------------------------
    // DashboardController::globalSearch
    // ---------------------------------------------------------------

    public function testDashboardGlobalSearchTooShort(): void
    {
        $controller = $this->createMockController(DashboardController::class);
        $meilisearch = $this->createStub(MeilisearchService::class);
        $request = new Request(['q' => 'a']);
        $response = $controller->globalSearch($request, $meilisearch);
        $this->assertInstanceOf(JsonResponse::class, $response);
        $this->assertSame('[]', $response->getContent());
    }

    public function testDashboardGlobalSearchEmptyQuery(): void
    {
        $controller = $this->createMockController(DashboardController::class);
        $meilisearch = $this->createStub(MeilisearchService::class);
        $request = new Request(['q' => '']);
        $response = $controller->globalSearch($request, $meilisearch);
        $this->assertInstanceOf(JsonResponse::class, $response);
        $this->assertSame('[]', $response->getContent());
    }

    public function testDashboardGlobalSearchReturnsResults(): void
    {
        $meilisearch = $this->createStub(MeilisearchService::class);
        $meilisearch->method('searchCustomers')->willReturn([['id' => 1, 'fullName' => 'Test Client', 'email' => 't@t.com']]);
        $meilisearch->method('searchDomains')->willReturn([]);
        $meilisearch->method('searchWebsites')->willReturn([]);
        $meilisearch->method('searchContacts')->willReturn([]);
        $meilisearch->method('searchRevendeurs')->willReturn([]);
        $meilisearch->method('searchDevis')->willReturn([]);
        $meilisearch->method('searchAdverts')->willReturn([]);
        $meilisearch->method('searchFactures')->willReturn([]);

        $controller = $this->createMockController(DashboardController::class);
        $request = new Request(['q' => 'test query']);
        $response = $controller->globalSearch($request, $meilisearch);
        $this->assertInstanceOf(JsonResponse::class, $response);

        $data = json_decode($response->getContent(), true);
        $this->assertNotEmpty($data);
        $this->assertSame('client', $data[0]['type']);
    }

    // ---------------------------------------------------------------
    // ServicesController missing methods
    // ---------------------------------------------------------------

    public function testServicesNdd(): void
    {
        $entityRepo = $this->createStub(EntityRepository::class);
        $entityRepo->method('findBy')->willReturn([]);

        $em = $this->createStub(EntityManagerInterface::class);
        $em->method('getRepository')->willReturn($entityRepo);

        $controller = $this->createMockController(ServicesController::class);
        $response = $controller->ndd($em);
        $this->assertInstanceOf(Response::class, $response);
    }

    public function testServicesNddSearch(): void
    {
        $meilisearch = $this->createStub(MeilisearchService::class);
        $meilisearch->method('searchDomains')->willReturn([['id' => 1, 'fqdn' => 'example.com']]);

        $controller = $this->createMockController(ServicesController::class);
        $request = new Request(['q' => 'example']);
        $response = $controller->nddSearch($request, $meilisearch);
        $this->assertInstanceOf(JsonResponse::class, $response);
    }

    public function testServicesNddSearchEmpty(): void
    {
        $meilisearch = $this->createStub(MeilisearchService::class);

        $controller = $this->createMockController(ServicesController::class);
        $request = new Request(['q' => '']);
        $response = $controller->nddSearch($request, $meilisearch);
        $this->assertInstanceOf(JsonResponse::class, $response);
        $this->assertSame('[]', $response->getContent());
    }

    public function testServicesEsyweb(): void
    {
        $entityRepo = $this->createStub(EntityRepository::class);
        $entityRepo->method('findBy')->willReturn([]);

        $em = $this->createStub(EntityManagerInterface::class);
        $em->method('getRepository')->willReturn($entityRepo);

        $controller = $this->createMockController(ServicesController::class);
        $response = $controller->esyweb($em);
        $this->assertInstanceOf(Response::class, $response);
    }

    public function testServicesEsywebSearch(): void
    {
        $meilisearch = $this->createStub(MeilisearchService::class);
        $meilisearch->method('searchWebsites')->willReturn([['id' => 1, 'name' => 'My Site']]);

        $controller = $this->createMockController(ServicesController::class);
        $request = new Request(['q' => 'my site']);
        $response = $controller->esywebSearch($request, $meilisearch);
        $this->assertInstanceOf(JsonResponse::class, $response);
    }

    public function testServicesEsywebSearchEmpty(): void
    {
        $meilisearch = $this->createStub(MeilisearchService::class);

        $controller = $this->createMockController(ServicesController::class);
        $request = new Request(['q' => '']);
        $response = $controller->esywebSearch($request, $meilisearch);
        $this->assertInstanceOf(JsonResponse::class, $response);
        $this->assertSame('[]', $response->getContent());
    }

    // ---------------------------------------------------------------
    // DashboardController::globalSearch — all result types populated
    // ---------------------------------------------------------------

    public function testDashboardGlobalSearchAllResultTypes(): void
    {
        $meilisearch = $this->createStub(MeilisearchService::class);
        $meilisearch->method('searchCustomers')->willReturn([
            ['id' => 1, 'fullName' => 'Test Client', 'email' => 't@t.com', 'raisonSociale' => null],
        ]);
        $meilisearch->method('searchDomains')->willReturn([
            ['id' => 2, 'fqdn' => 'example.com', 'customerName' => 'Test Client', 'customerId' => 1],
        ]);
        $meilisearch->method('searchWebsites')->willReturn([
            ['id' => 3, 'name' => 'My Site', 'customerName' => 'Test Client', 'customerId' => 1],
        ]);
        $meilisearch->method('searchContacts')->willReturn([
            ['id' => 4, 'fullName' => 'Jean Dupont', 'role' => 'Directeur', 'email' => 'j@t.com', 'customerId' => 1],
        ]);
        $meilisearch->method('searchRevendeurs')->willReturn([
            ['id' => 5, 'fullName' => 'Revendeur ABC', 'raisonSociale' => null, 'codeRevendeur' => 'REV001'],
        ]);
        $meilisearch->method('searchDevis')->willReturn([
            ['id' => 6, 'numOrder' => 'D-2026-001', 'customerName' => 'Test Client', 'totalTtc' => '120.00', 'customerId' => 1],
        ]);
        $meilisearch->method('searchAdverts')->willReturn([
            ['id' => 7, 'numOrder' => 'A-2026-001', 'customerName' => 'Test Client', 'totalTtc' => '240.00', 'customerId' => 1],
        ]);
        $meilisearch->method('searchFactures')->willReturn([
            ['id' => 8, 'invoiceNumber' => 'F-2026-001', 'customerName' => 'Test Client', 'totalTtc' => '300.00', 'customerId' => 1],
        ]);

        $controller = $this->createMockController(DashboardController::class);
        $request = new Request(['q' => 'test query']);
        $response = $controller->globalSearch($request, $meilisearch);
        $this->assertInstanceOf(JsonResponse::class, $response);

        $data = json_decode($response->getContent(), true);
        $this->assertCount(8, $data);

        $types = array_column($data, 'type');
        $this->assertContains('client', $types);
        $this->assertContains('ndd', $types);
        $this->assertContains('site', $types);
        $this->assertContains('contact', $types);
        $this->assertContains('revendeur', $types);
        $this->assertContains('devis', $types);
        $this->assertContains('avis', $types);
        $this->assertContains('facture', $types);
    }

    public function testDashboardGlobalSearchContactWithNoEmail(): void
    {
        $meilisearch = $this->createStub(MeilisearchService::class);
        $meilisearch->method('searchCustomers')->willReturn([]);
        $meilisearch->method('searchDomains')->willReturn([]);
        $meilisearch->method('searchWebsites')->willReturn([]);
        $meilisearch->method('searchContacts')->willReturn([
            ['id' => 1, 'fullName' => 'Sans Email', 'role' => 'DG', 'email' => null, 'customerId' => 2],
        ]);
        $meilisearch->method('searchRevendeurs')->willReturn([]);
        $meilisearch->method('searchDevis')->willReturn([]);
        $meilisearch->method('searchAdverts')->willReturn([]);
        $meilisearch->method('searchFactures')->willReturn([]);

        $controller = $this->createMockController(DashboardController::class);
        $request = new Request(['q' => 'Sans Email']);
        $response = $controller->globalSearch($request, $meilisearch);
        $this->assertInstanceOf(JsonResponse::class, $response);

        $data = json_decode($response->getContent(), true);
        $this->assertCount(1, $data);
        $this->assertSame('contact', $data[0]['type']);
    }
}
