<?php

declare(strict_types=1);

namespace App\Shared\Schema;

use App\Shared\Security\RbacSupport;
use PDO;
use Throwable;

final class ChecksSchemaSupport
{
    public static function ensureChecksSchema(PDO $pdo): void
    {
        RbacSupport::ensurePermissionsSeed($pdo);
        PartySchemaSupport::ensurePartiesSchema($pdo);

        try {
            $pdo->exec("CREATE TABLE IF NOT EXISTS checks (
                id BIGINT AUTO_INCREMENT PRIMARY KEY,
                check_no VARCHAR(100) NOT NULL,
                amount DECIMAL(18,2) NOT NULL,
                drawer_party_id BIGINT UNSIGNED NOT NULL,
                bank_name VARCHAR(150) NULL,
                issue_date DATE NULL,
                due_date DATE NULL,
                receive_date DATETIME NOT NULL,
                current_status ENUM('received','endorsed','returned','settled_cash','replaced','canceled') NOT NULL DEFAULT 'received',
                current_holder_type ENUM('company','supplier','customer') NOT NULL DEFAULT 'company',
                current_holder_party_id BIGINT UNSIGNED NULL,
                last_endorsed_party_id BIGINT UNSIGNED NULL,
                notes TEXT NULL,
                user_id BIGINT UNSIGNED NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                KEY idx_checks_status_due (current_status, due_date),
                KEY idx_checks_drawer (drawer_party_id),
                CONSTRAINT fk_checks_drawer_party FOREIGN KEY (drawer_party_id) REFERENCES parties(id)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
        } catch (Throwable $e) {
        }

        try {
            $pdo->exec("CREATE TABLE IF NOT EXISTS check_movements (
                id BIGINT AUTO_INCREMENT PRIMARY KEY,
                check_id BIGINT NOT NULL,
                movement_type ENUM('receive','endorse','return','cash_settlement','replace') NOT NULL,
                movement_date DATETIME NOT NULL,
                party_id BIGINT UNSIGNED NULL,
                amount DECIMAL(18,2) NOT NULL,
                notes TEXT NULL,
                user_id BIGINT UNSIGNED NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                KEY idx_check_movements_check_date (check_id, movement_date),
                CONSTRAINT fk_check_movements_check FOREIGN KEY (check_id) REFERENCES checks(id) ON DELETE CASCADE
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
        } catch (Throwable $e) {
        }
    }
}
