<?php

declare(strict_types=1);

namespace ApiModel\Tests\Integration\Http;

use ApiModel\Action\OrganizationAction;
use ApiModel\Infrastructure\Persistence\Repositories\PdoBranchRepository;
use ApiModel\Infrastructure\Persistence\Repositories\PdoCompanyRepository;
use ApiModel\Infrastructure\Persistence\Repositories\PdoProfileRepository;
use ApiModel\Infrastructure\Persistence\Repositories\PdoUserAccessRepository;
use ApiModel\Middleware\CompanyContextMiddleware;
use ApiModel\Middleware\ApiErrorHandler;
use ApiModel\Route\OrganizationRoutes;
use ApiModel\Service\OrganizationService;
use ApiModel\Shared\Support\HttpRunner;
use Firebase\JWT\JWT;
use PDO;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ResponseInterface;
use Slim\App;
use Slim\Factory\AppFactory;
use Slim\Psr7\Factory\ServerRequestFactory;
use Slim\Psr7\Factory\StreamFactory;

final class OrganizationRoutesTest extends TestCase
{
    private PDO $pdo;
    private App $app;
    private string $adminToken;
    private string $managerToken;

    private const ADMIN_USER_ID = '11111111-1111-1111-1111-111111111111';
    private const MANAGER_USER_ID = '22222222-2222-2222-2222-222222222222';
    private const ADMIN_ROLE_ID = '33333333-3333-3333-3333-333333333333';
    private const MANAGER_ROLE_ID = '44444444-4444-4444-4444-444444444444';
    private const COMPANY_ID = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
    private const BRANCH_ID = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb';

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

        $this->pdo = new PDO('sqlite::memory:');
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

        $this->createSchema();
        $this->seedData();
        $this->configureEnv();

        $this->app = $this->buildApp();

        $this->adminToken = $this->issueToken(self::ADMIN_USER_ID, 'ADMINISTRADOR');
        $this->managerToken = $this->issueToken(self::MANAGER_USER_ID, 'MANAGER');
    }

    public function testGetMyContextReturnsCompaniesForAdmin(): void
    {
        $response = $this->request('GET', '/organization/my-context', [
            'Authorization' => 'Bearer ' . $this->adminToken,
        ]);

        $this->assertSame(200, $response->getStatusCode());
        $body = $this->decodeBody($response);

        $this->assertArrayHasKey('companies', $body);
        $this->assertCount(1, $body['companies']);
        $this->assertSame(self::COMPANY_ID, $body['default_company_id']);
    }

    public function testListCompaniesAsAdmin(): void
    {
        $response = $this->request('GET', '/organization/companies', [
            'Authorization' => 'Bearer ' . $this->adminToken,
        ]);

        $this->assertSame(200, $response->getStatusCode());
        $body = $this->decodeBody($response);
        $this->assertCount(1, $body);
        $this->assertSame('Empresa Demo', $body[0]['legal_name']);
    }

    public function testListCompaniesAsManagerReturns403(): void
    {
        $response = $this->request('GET', '/organization/companies', [
            'Authorization' => 'Bearer ' . $this->managerToken,
        ]);

        $this->assertSame(403, $response->getStatusCode());
    }

    public function testCreateCompanyAsAdmin(): void
    {
        $response = $this->jsonRequest('POST', '/organization/companies', [
            'legal_name' => 'Nueva Empresa S.A.',
            'trade_name' => 'Nueva',
            'tax_id' => '800999888-7',
            'base_currency' => 'COP',
        ], [
            'Authorization' => 'Bearer ' . $this->adminToken,
        ]);

        $this->assertSame(200, $response->getStatusCode());
        $body = $this->decodeBody($response);
        $this->assertSame('Nueva Empresa S.A.', $body['legal_name']);
        $this->assertSame('800999888-7', $body['tax_id']);
    }

    public function testAccountingRouteRequiresCompanyHeader(): void
    {
        $response = $this->request('GET', '/accounting/chart', [
            'Authorization' => 'Bearer ' . $this->adminToken,
        ]);

        $this->assertSame(400, $response->getStatusCode());
    }

    public function testAccountingRouteRejectsInvalidCompanyAccess(): void
    {
        $response = $this->request('GET', '/accounting/chart', [
            'Authorization' => 'Bearer ' . $this->managerToken,
            'X-Company-Id' => self::COMPANY_ID,
        ]);

        $this->assertSame(403, $response->getStatusCode());
    }

    public function testCreateBranchWithOperatingCurrency(): void
    {
        $response = $this->jsonRequest('POST', '/organization/companies/' . self::COMPANY_ID . '/branches', [
            'name' => 'Bogotá',
            'code' => 'BOG',
            'operating_currency' => 'COP',
            'is_main' => false,
        ], [
            'Authorization' => 'Bearer ' . $this->adminToken,
        ]);

        $this->assertSame(200, $response->getStatusCode());
        $body = $this->decodeBody($response);
        $this->assertSame('COP', $body['operating_currency']);
        $this->assertSame('USD', $body['functional_currency']);
    }

    public function testDeleteMainBranchReturns400(): void
    {
        $response = $this->request('DELETE', '/organization/branches/' . self::BRANCH_ID, [
            'Authorization' => 'Bearer ' . $this->adminToken,
        ]);

        $this->assertSame(400, $response->getStatusCode());
    }

    public function testDeleteBranchAsNonAdminReturns403(): void
    {
        $response = $this->request('DELETE', '/organization/branches/' . self::BRANCH_ID, [
            'Authorization' => 'Bearer ' . $this->managerToken,
        ]);

        $this->assertSame(403, $response->getStatusCode());
    }

    public function testDeleteNonExistentBranchReturns404(): void
    {
        $response = $this->request('DELETE', '/organization/branches/99999999-9999-9999-9999-999999999999', [
            'Authorization' => 'Bearer ' . $this->adminToken,
        ]);

        $this->assertSame(404, $response->getStatusCode());
    }

    public function testDeleteBranchSuccess(): void
    {
        // 1. Create a non-main branch
        $branchId = 'dddddddd-dddd-dddd-dddd-dddddddddddd';
        $this->pdo->prepare(
            'INSERT INTO branches (id, company_id, name, code, is_main, operating_currency, is_active)
             VALUES (?,?,?,?,0,?,1)'
        )->execute([$branchId, self::COMPANY_ID, 'Sucursal Test', 'TEST', 'USD']);

        // 2. Delete it
        $response = $this->request('DELETE', '/organization/branches/' . $branchId, [
            'Authorization' => 'Bearer ' . $this->adminToken,
        ]);

        $this->assertSame(200, $response->getStatusCode());
        $body = $this->decodeBody($response);
        $this->assertTrue($body['ok'] ?? false);

        // 3. Verify it is gone
        $st = $this->pdo->prepare('SELECT * FROM branches WHERE id = ?');
        $st->execute([$branchId]);
        $this->assertFalse($st->fetch());
    }


    private function buildApp(): App
    {
        $app = AppFactory::create();

        $organizationService = new OrganizationService(
            new PdoCompanyRepository($this->pdo),
            new PdoBranchRepository($this->pdo),
            new PdoUserAccessRepository($this->pdo),
            new PdoProfileRepository($this->pdo),
        );

        $organizationAction = new OrganizationAction($organizationService);
        $companyMiddleware = new CompanyContextMiddleware($organizationService);

        $uuid = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';
        $app->group('', function ($g) use ($organizationAction, $uuid): void {
            OrganizationRoutes::register($g, $organizationAction, $uuid);
            $g->get('/accounting/chart', fn ($request, $response) => HttpRunner::runJson($request, $response, fn () => ['ok' => true]));
        });

        $app->addRoutingMiddleware();
        $app->add($companyMiddleware);
        $errorMiddleware = $app->addErrorMiddleware(false, true, true);
        $errorMiddleware->setDefaultErrorHandler(ApiErrorHandler::create($app->getResponseFactory()));

        return $app;
    }

    private function request(string $method, string $path, array $headers = []): ResponseInterface
    {
        $requestFactory = new ServerRequestFactory();
        $request = $requestFactory->createServerRequest($method, $path);
        foreach ($headers as $name => $value) {
            $request = $request->withHeader($name, $value);
        }

        return $this->app->handle($request);
    }

    private function jsonRequest(string $method, string $path, array $payload, array $headers = []): ResponseInterface
    {
        $streamFactory = new StreamFactory();
        $requestFactory = new ServerRequestFactory();
        $body = $streamFactory->createStream((string) json_encode($payload, JSON_THROW_ON_ERROR));

        $request = $requestFactory
            ->createServerRequest($method, $path)
            ->withHeader('Content-Type', 'application/json')
            ->withBody($body);

        foreach ($headers as $name => $value) {
            $request = $request->withHeader($name, $value);
        }

        return $this->app->handle($request);
    }

    /** @return array<string, mixed> */
    private function decodeBody(ResponseInterface $response): array
    {
        $raw = (string) $response->getBody();
        $data = json_decode($raw, true);

        return is_array($data) ? $data : [];
    }

    private function issueToken(string $userId, string $role): string
    {
        return JWT::encode([
            'sub' => $userId,
            'role' => $role,
            'lang' => 'es',
            'iat' => time(),
            'exp' => time() + 3600,
        ], (string) $_ENV['JWT_SECRET'], 'HS256');
    }

    private function createSchema(): void
    {
        $this->pdo->exec("ATTACH DATABASE ':memory:' AS auth");

        $this->pdo->exec(
            'CREATE TABLE auth.roles (
                id TEXT PRIMARY KEY,
                name_es TEXT NOT NULL UNIQUE,
                name_en TEXT NOT NULL UNIQUE,
                description_es TEXT,
                description_en TEXT,
                is_active INTEGER NOT NULL DEFAULT 1
            )',
        );

        $this->pdo->exec(
            'CREATE TABLE auth.users (
                id TEXT PRIMARY KEY,
                name TEXT NOT NULL,
                email TEXT NOT NULL UNIQUE,
                password_hash TEXT NULL,
                language TEXT NOT NULL DEFAULT "es",
                is_active INTEGER NOT NULL DEFAULT 1
            )',
        );

        $this->pdo->exec(
            'CREATE TABLE auth.role_user (
                role_id TEXT NOT NULL,
                user_id TEXT NOT NULL,
                PRIMARY KEY (role_id, user_id)
            )',
        );

        $this->pdo->exec(
            'CREATE TABLE auth.module (
                id TEXT PRIMARY KEY,
                name_es TEXT NOT NULL,
                name_en TEXT NOT NULL,
                icon TEXT,
                order_index INTEGER DEFAULT 0,
                is_active INTEGER NOT NULL DEFAULT 1
            )',
        );

        $this->pdo->exec(
            'CREATE TABLE auth.page (
                id TEXT PRIMARY KEY,
                module_id TEXT NOT NULL,
                name_es TEXT NOT NULL,
                name_en TEXT NOT NULL,
                path TEXT NOT NULL UNIQUE,
                icon TEXT,
                order_index INTEGER DEFAULT 0,
                is_active INTEGER NOT NULL DEFAULT 1
            )',
        );

        $this->pdo->exec(
            'CREATE TABLE auth.profile (
                id TEXT PRIMARY KEY,
                role_id TEXT NOT NULL,
                page_id TEXT NOT NULL,
                can_view INTEGER NOT NULL DEFAULT 0,
                can_create INTEGER NOT NULL DEFAULT 0,
                can_edit INTEGER NOT NULL DEFAULT 0,
                can_delete INTEGER NOT NULL DEFAULT 0,
                UNIQUE (role_id, page_id)
            )',
        );

        $this->pdo->exec(
            'CREATE TABLE companies (
                id TEXT PRIMARY KEY,
                legal_name TEXT NOT NULL,
                trade_name TEXT,
                tax_id TEXT NOT NULL UNIQUE,
                base_currency TEXT NOT NULL DEFAULT "USD",
                email TEXT,
                phone TEXT,
                address TEXT,
                is_active INTEGER NOT NULL DEFAULT 1,
                created_at TEXT DEFAULT CURRENT_TIMESTAMP,
                updated_at TEXT DEFAULT CURRENT_TIMESTAMP
            )',
        );

        $this->pdo->exec(
            'CREATE TABLE branches (
                id TEXT PRIMARY KEY,
                company_id TEXT NOT NULL,
                name TEXT NOT NULL,
                code TEXT,
                address TEXT,
                phone TEXT,
                is_main INTEGER NOT NULL DEFAULT 0,
                operating_currency TEXT NOT NULL DEFAULT "USD",
                is_active INTEGER NOT NULL DEFAULT 1,
                created_at TEXT DEFAULT CURRENT_TIMESTAMP,
                updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
                UNIQUE (company_id, code)
            )',
        );

        $this->pdo->exec(
            'CREATE TABLE user_access (
                id TEXT PRIMARY KEY,
                user_id TEXT NOT NULL,
                company_id TEXT NOT NULL,
                branch_id TEXT,
                can_manage INTEGER NOT NULL DEFAULT 0,
                is_default INTEGER NOT NULL DEFAULT 0,
                created_at TEXT DEFAULT CURRENT_TIMESTAMP,
                UNIQUE (user_id, company_id)
            )',
        );
    }

    private function seedData(): void
    {
        $this->pdo->prepare(
            'INSERT INTO auth.users (id, name, email, password_hash, is_active) VALUES (?,?,?, "hash", 1)'
        )->execute([self::ADMIN_USER_ID, 'Admin User', 'admin@example.com']);

        $this->pdo->prepare(
            'INSERT INTO auth.users (id, name, email, password_hash, is_active) VALUES (?,?,?, "hash", 1)'
        )->execute([self::MANAGER_USER_ID, 'Manager User', 'manager@example.com']);

        $this->pdo->prepare(
            'INSERT INTO auth.roles (id, name_es, name_en) VALUES (?,?,?)'
        )->execute([self::ADMIN_ROLE_ID, 'ADMINISTRADOR', 'ADMINISTRATOR']);

        $this->pdo->prepare(
            'INSERT INTO auth.roles (id, name_es, name_en) VALUES (?,?,?)'
        )->execute([self::MANAGER_ROLE_ID, 'MANAGER', 'MANAGER']);

        $this->pdo->prepare('INSERT INTO auth.role_user (role_id, user_id) VALUES (?,?)')
            ->execute([self::ADMIN_ROLE_ID, self::ADMIN_USER_ID]);

        $this->pdo->prepare('INSERT INTO auth.role_user (role_id, user_id) VALUES (?,?)')
            ->execute([self::MANAGER_ROLE_ID, self::MANAGER_USER_ID]);

        $this->pdo->prepare(
            'INSERT INTO companies (id, legal_name, trade_name, tax_id, base_currency, is_active)
             VALUES (?,?,?,?,?,1)'
        )->execute([self::COMPANY_ID, 'Empresa Demo', 'Demo', '900111222-3', 'USD']);

        $this->pdo->prepare(
            'INSERT INTO branches (id, company_id, name, code, is_main, operating_currency, is_active)
             VALUES (?,?,?,?,1,?,1)'
        )->execute([self::BRANCH_ID, self::COMPANY_ID, 'Principal', 'MAIN', 'USD']);

        $this->pdo->prepare(
            'INSERT INTO user_access (id, user_id, company_id, branch_id, can_manage, is_default)
             VALUES (?,?,?,?,1,1)'
        )->execute(['cccccccc-cccc-cccc-cccc-cccccccccccc', self::ADMIN_USER_ID, self::COMPANY_ID, self::BRANCH_ID]);
    }

    private function configureEnv(): void
    {
        $_ENV['JWT_SECRET'] = 'test-jwt-secret';
        $_ENV['JWT_EXPIRES_IN'] = '15m';
        $_ENV['JWT_REFRESH_EXPIRES_DAYS'] = '7';
        $_ENV['JWT_KID'] = '';
        $_ENV['JWT_SECRET_PREVIOUS'] = '';
    }
}
