<?php

declare(strict_types=1);

namespace ApiModel\Tests\Integration\Http;

use ApiModel\Action\InventoryAction;
use ApiModel\Infrastructure\Persistence\Repositories\PdoInventoryRepository;
use ApiModel\Infrastructure\Persistence\Repositories\PdoInventoryAdjustmentRepository;
use ApiModel\Infrastructure\Persistence\Repositories\PdoInventoryTransferRepository;
use ApiModel\Infrastructure\Persistence\Repositories\PdoJournalRepository;
use ApiModel\Infrastructure\Persistence\Repositories\PdoChartAccountRepository;
use ApiModel\Infrastructure\Persistence\Repositories\PdoExchangeRateRepository;
use ApiModel\Infrastructure\Persistence\Repositories\PdoCompanyRepository;
use ApiModel\Infrastructure\Persistence\Repositories\PdoBranchRepository;
use ApiModel\Infrastructure\Persistence\Repositories\PdoUserAccessRepository;
use ApiModel\Infrastructure\Persistence\Repositories\PdoProfileRepository;
use ApiModel\Infrastructure\Persistence\Repositories\PdoTaxRateRepository;
use ApiModel\Middleware\CompanyContextMiddleware;
use ApiModel\Middleware\ApiErrorHandler;
use ApiModel\Route\InventoryRoutes;
use ApiModel\Service\InventoryService;
use ApiModel\Service\InventoryAdjustmentService;
use ApiModel\Service\InventoryTransferService;
use ApiModel\Service\JournalService;
use ApiModel\Service\OrganizationService;
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 InventoryAdjustmentsRoutesTest extends TestCase
{
    private PDO $pdo;
    private App $app;
    private string $adminToken;

    private const ADMIN_USER_ID = '11111111-1111-1111-1111-111111111111';
    private const ADMIN_ROLE_ID = '33333333-3333-3333-3333-333333333333';
    private const COMPANY_ID = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
    private const BRANCH_ID = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb';

    private const INVENTORY_ACCOUNT_ID = 'acc-inv';
    private const COUNTERPART_ACCOUNT_ID = 'acc-counterpart';

    private string $itemId;
    private string $warehouseId;

    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');

        // Create initial item and warehouse for adjustment tests
        $this->itemId = 'item-1';
        $this->warehouseId = 'wh-1';

        $this->pdo->exec("INSERT INTO chart_accounts (id, company_id, code, name, account_type) VALUES ('" . self::INVENTORY_ACCOUNT_ID . "', '" . self::COMPANY_ID . "', '1435', 'Inventario', 'asset')");
        $this->pdo->exec("INSERT INTO chart_accounts (id, company_id, code, name, account_type) VALUES ('" . self::COUNTERPART_ACCOUNT_ID . "', '" . self::COMPANY_ID . "', '5199', 'Ajuste costo', 'expense')");

        $this->pdo->exec("INSERT INTO inventory_items (id, company_id, sku, name, item_type, inventory_account_id, is_active) VALUES ('{$this->itemId}', '" . self::COMPANY_ID . "', 'SKU-TEST', 'Item Test', 'product', '" . self::INVENTORY_ACCOUNT_ID . "', 1)");
        $this->pdo->exec("INSERT INTO warehouses (id, company_id, name, code, is_active) VALUES ('{$this->warehouseId}', '" . self::COMPANY_ID . "', 'Bodega Central', 'W-CENTRAL', 1)");
    }

    private function companyHeaders(): array
    {
        return [
            'Authorization' => 'Bearer ' . $this->adminToken,
            'X-Company-Id' => self::COMPANY_ID,
        ];
    }

    public function testListAdjustmentsInitiallyEmpty(): void
    {
        $response = $this->request('GET', '/inventory/adjustments', $this->companyHeaders());
        $this->assertSame(200, $response->getStatusCode());
        $body = $this->decodeBody($response);
        $this->assertCount(0, $body);
    }

    public function testAdjustmentCrud(): void
    {
        // 1. Create Adjustment (Increment Stock by 10)
        $payload = [
            'adjustment_date' => '2026-06-22',
            'notes' => 'Ajuste de entrada inicial',
            'lines' => [
                [
                    'item_id' => $this->itemId,
                    'warehouse_id' => $this->warehouseId,
                    'quantity' => 10.0,
                    'unit_cost' => 15.0,
                    'chart_account_id' => self::COUNTERPART_ACCOUNT_ID,
                ]
            ]
        ];

        $response = $this->jsonRequest('POST', '/inventory/adjustments', $payload, $this->companyHeaders());
        if ($response->getStatusCode() !== 200) {
            echo "\nSTATUS: " . $response->getStatusCode() . "\n";
            echo "BODY: " . (string)$response->getBody() . "\n";
        }
        $this->assertSame(200, $response->getStatusCode());
        $created = $this->decodeBody($response);
        $this->assertArrayHasKey('id', $created);
        $this->assertSame('Ajuste de entrada inicial', $created['notes']);

        $adjustmentId = $created['id'];
        $adjNumber = $created['adjustment_number'];

        // Assert Stock updated
        $stmtStock = $this->pdo->prepare('SELECT quantity FROM inventory_stock WHERE item_id = ? AND warehouse_id = ?');
        $stmtStock->execute([$this->itemId, $this->warehouseId]);
        $this->assertEquals(10.0, $stmtStock->fetchColumn());

        // Assert Accounting Journal Entry created
        $stmtJe = $this->pdo->prepare('SELECT id, entry_number, status FROM journal_entries WHERE entry_number = ? LIMIT 1');
        $stmtJe->execute([$adjNumber]);
        $je = $stmtJe->fetch();
        $this->assertNotFalse($je);

        // Assert Journal lines (Debit Asset Inventory, Credit Counterpart Expense/Income)
        $stmtJl = $this->pdo->prepare('SELECT chart_account_id, debit, credit FROM journal_lines WHERE journal_entry_id = ? ORDER BY line_order ASC');
        $stmtJl->execute([$je['id']]);
        $jl = $stmtJl->fetchAll();
        $this->assertCount(2, $jl);
        // Debit Inventory: 10 * 15 = 150.0
        $this->assertSame(self::INVENTORY_ACCOUNT_ID, $jl[0]['chart_account_id']);
        $this->assertEquals(150.0, $jl[0]['debit']);
        $this->assertEquals(0.0, $jl[0]['credit']);
        // Credit Counterpart: 150.0
        $this->assertSame(self::COUNTERPART_ACCOUNT_ID, $jl[1]['chart_account_id']);
        $this->assertEquals(0.0, $jl[1]['debit']);
        $this->assertEquals(150.0, $jl[1]['credit']);

        // 2. Edit/Update Adjustment (Change quantity to 8, meaning stock should become 8)
        $editPayload = [
            'adjustment_date' => '2026-06-22',
            'notes' => 'Ajuste corregido',
            'lines' => [
                [
                    'item_id' => $this->itemId,
                    'warehouse_id' => $this->warehouseId,
                    'quantity' => 8.0,
                    'unit_cost' => 15.0,
                    'chart_account_id' => self::COUNTERPART_ACCOUNT_ID,
                ]
            ]
        ];
        $editResponse = $this->jsonRequest('PATCH', '/inventory/adjustments/' . $adjustmentId, $editPayload, $this->companyHeaders());
        $this->assertSame(200, $editResponse->getStatusCode());
        $edited = $this->decodeBody($editResponse);
        $this->assertSame('Ajuste corregido', $edited['notes']);

        // Assert Stock updated to 8
        $stmtStock->execute([$this->itemId, $this->warehouseId]);
        $this->assertEquals(8.0, $stmtStock->fetchColumn());

        // Assert Journal entry updated (total should be 120.0 now)
        $stmtJe->execute([$adjNumber]);
        $je = $stmtJe->fetch();
        $this->assertNotFalse($je);
        $stmtJl->execute([$je['id']]);
        $jl = $stmtJl->fetchAll();
        $this->assertCount(2, $jl);
        $this->assertEquals(120.0, $jl[0]['debit']);

        // 3. Delete Adjustment
        $delResponse = $this->request('DELETE', '/inventory/adjustments/' . $adjustmentId, $this->companyHeaders());
        $this->assertSame(200, $delResponse->getStatusCode());

        // Assert Stock reverted to 0
        $stmtStock->execute([$this->itemId, $this->warehouseId]);
        $this->assertEquals(0.0, $stmtStock->fetchColumn());

        // Assert Journal entry deleted
        $stmtJeCount = $this->pdo->prepare('SELECT COUNT(*) FROM journal_entries WHERE entry_number = ?');
        $stmtJeCount->execute([$adjNumber]);
        $this->assertEquals(0, $stmtJeCount->fetchColumn());
    }

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

        $orgRepo = new PdoCompanyRepository($this->pdo);
        $branchRepo = new PdoBranchRepository($this->pdo);
        $uaRepo = new PdoUserAccessRepository($this->pdo);
        $profRepo = new PdoProfileRepository($this->pdo);
        $orgService = new OrganizationService($orgRepo, $branchRepo, $uaRepo, $profRepo);
        
        $companyMiddleware = new CompanyContextMiddleware($orgService);

        $inventoryRepo = new PdoInventoryRepository($this->pdo);
        $adjustmentRepo = new PdoInventoryAdjustmentRepository($this->pdo);
        $transferRepo = new PdoInventoryTransferRepository($this->pdo);
        $journalRepo = new PdoJournalRepository($this->pdo);
        $chartAccountRepo = new PdoChartAccountRepository($this->pdo);
        $exchangeRateRepo = new PdoExchangeRateRepository($this->pdo);

        $journalService = new JournalService($journalRepo, $chartAccountRepo, $orgRepo, $branchRepo, $exchangeRateRepo);
        
        $inventoryService = new InventoryService($inventoryRepo);
        $adjustmentService = new InventoryAdjustmentService($adjustmentRepo, $inventoryRepo, $journalRepo, $journalService, $this->pdo);
        $transferService = new InventoryTransferService($transferRepo, $inventoryRepo, $this->pdo);

        $action = new InventoryAction($inventoryService, $adjustmentService, $transferService);

        $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 ($action, $uuid): void {
            InventoryRoutes::register($g, $action, $uuid);
        });

        $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);
    }

    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 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)
            )'
        );

        $this->pdo->exec(
            'CREATE TABLE chart_accounts (
                id TEXT PRIMARY KEY,
                parent_id TEXT NULL,
                company_id TEXT NOT NULL,
                code TEXT NOT NULL,
                name TEXT NOT NULL,
                account_type TEXT NOT NULL,
                is_header INTEGER NOT NULL DEFAULT 0,
                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 tax_rates (
                id TEXT PRIMARY KEY,
                company_id TEXT NOT NULL REFERENCES companies(id),
                name TEXT NOT NULL,
                rate REAL NOT NULL,
                type TEXT NOT NULL,
                is_active INTEGER NOT NULL DEFAULT 1,
                created_at TEXT DEFAULT CURRENT_TIMESTAMP,
                updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
                UNIQUE (company_id, name)
            )'
        );

        $this->pdo->exec(
            'CREATE TABLE inventory_categories (
                id TEXT PRIMARY KEY,
                company_id TEXT NOT NULL REFERENCES companies(id),
                name TEXT NOT NULL,
                description TEXT NULL,
                created_at TEXT DEFAULT CURRENT_TIMESTAMP,
                updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
                UNIQUE (company_id, name)
            )'
        );

        $this->pdo->exec(
            'CREATE TABLE inventory_items (
                id TEXT PRIMARY KEY,
                company_id TEXT NOT NULL REFERENCES companies(id),
                category_id TEXT NULL,
                sku TEXT NOT NULL,
                name TEXT NOT NULL,
                description TEXT NULL,
                item_type TEXT NOT NULL DEFAULT "product",
                sale_price REAL NOT NULL DEFAULT 0.0,
                purchase_price REAL NOT NULL DEFAULT 0.0,
                tax_rate_id TEXT NULL,
                income_account_id TEXT NULL,
                expense_account_id TEXT NULL,
                inventory_account_id TEXT NULL,
                is_active INTEGER NOT NULL DEFAULT 1,
                created_at TEXT DEFAULT CURRENT_TIMESTAMP,
                updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
                UNIQUE (company_id, sku)
            )'
        );

        $this->pdo->exec(
            'CREATE TABLE warehouses (
                id TEXT PRIMARY KEY,
                company_id TEXT NOT NULL REFERENCES companies(id),
                name TEXT NOT NULL,
                code TEXT NOT NULL,
                address TEXT NULL,
                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 inventory_stock (
                item_id TEXT NOT NULL REFERENCES inventory_items(id),
                warehouse_id TEXT NOT NULL REFERENCES warehouses(id),
                quantity REAL NOT NULL DEFAULT 0.0,
                PRIMARY KEY (item_id, warehouse_id)
            )'
        );

        $this->pdo->exec(
            'CREATE TABLE inventory_adjustments (
                id TEXT PRIMARY KEY,
                company_id TEXT NOT NULL REFERENCES companies(id),
                branch_id TEXT,
                adjustment_number TEXT NOT NULL,
                adjustment_date TEXT NOT NULL,
                notes TEXT,
                created_by TEXT,
                created_at TEXT DEFAULT CURRENT_TIMESTAMP,
                updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
                UNIQUE (company_id, adjustment_number)
            )'
        );

        $this->pdo->exec(
            'CREATE TABLE inventory_adjustment_lines (
                id TEXT PRIMARY KEY,
                adjustment_id TEXT NOT NULL REFERENCES inventory_adjustments(id),
                item_id TEXT NOT NULL REFERENCES inventory_items(id),
                warehouse_id TEXT NOT NULL REFERENCES warehouses(id),
                quantity REAL NOT NULL,
                unit_cost REAL NOT NULL DEFAULT 0.0,
                chart_account_id TEXT NOT NULL
            )'
        );

        $this->pdo->exec(
            'CREATE TABLE journal_entries (
                id TEXT PRIMARY KEY,
                company_id TEXT NOT NULL,
                branch_id TEXT,
                entry_number TEXT NOT NULL,
                entry_date TEXT NOT NULL,
                description TEXT,
                status TEXT NOT NULL DEFAULT "draft",
                operating_currency TEXT NOT NULL,
                functional_currency TEXT NOT NULL,
                exchange_rate REAL NOT NULL,
                created_by TEXT,
                created_at TEXT DEFAULT CURRENT_TIMESTAMP,
                updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
                UNIQUE (company_id, entry_number)
            )'
        );

        $this->pdo->exec(
            'CREATE TABLE journal_lines (
                id TEXT PRIMARY KEY,
                journal_entry_id TEXT NOT NULL REFERENCES journal_entries(id),
                chart_account_id TEXT NOT NULL REFERENCES chart_accounts(id),
                description TEXT,
                debit REAL NOT NULL DEFAULT 0,
                credit REAL NOT NULL DEFAULT 0,
                debit_functional REAL NOT NULL DEFAULT 0,
                credit_functional REAL NOT NULL DEFAULT 0,
                line_order INTEGER NOT NULL DEFAULT 0
            )'
        );
    }

    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.roles (id, name_es, name_en) VALUES (?,?,?)'
        )->execute([self::ADMIN_ROLE_ID, 'ADMINISTRADOR', 'ADMINISTRATOR']);

        $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 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'] = '';
    }
}
