<?php

declare(strict_types=1);

namespace App\Shared\Schema;

use PDO;
use Throwable;

final class SupplierLedgerSchemaSupport
{
    public static function ensureSupplierLedgerSchema(PDO $pdo): void
    {
        if (SchemaSupport::tableExists($pdo, 'supplier_ledger')) {
            try {
                // no-op; keep parity with legacy behaviour
            } catch (Throwable $e) {
            }
            return;
        }

        if (!SchemaSupport::tableExists($pdo, 'suppliers')) {
            $pdo->exec("CREATE TABLE IF NOT EXISTS suppliers (
                id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
                code VARCHAR(60) DEFAULT NULL,
                name VARCHAR(150) NOT NULL,
                phone VARCHAR(60) DEFAULT NULL,
                is_active TINYINT(1) NOT NULL DEFAULT 1,
                created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
                PRIMARY KEY (id),
                KEY idx_suppliers_name (name)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;");
        }

        $pdo->exec("CREATE TABLE IF NOT EXISTS supplier_ledger (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            supplier_id BIGINT UNSIGNED NOT NULL,
            doc_type VARCHAR(30) NOT NULL,
            doc_id BIGINT UNSIGNED NOT NULL,
            doc_no VARCHAR(60) DEFAULT NULL,
            doc_date DATETIME NOT NULL,
            debit DECIMAL(14,2) NOT NULL DEFAULT 0.00,
            credit DECIMAL(14,2) NOT NULL DEFAULT 0.00,
            notes VARCHAR(255) DEFAULT NULL,
            created_by BIGINT UNSIGNED DEFAULT NULL,
            created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY idx_supplier_ledger_supplier (supplier_id),
            KEY idx_supplier_ledger_date (doc_date),
            KEY idx_supplier_ledger_doc (doc_type, doc_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;");
    }
}
