CREATE TABLE IF NOT EXISTS finance_reconciliation (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    tenant_id BIGINT UNSIGNED NOT NULL,
    project_id BIGINT UNSIGNED NOT NULL,
    expected_amount_cent BIGINT NOT NULL DEFAULT 0,
    actual_amount_cent BIGINT NOT NULL DEFAULT 0,
    diff_amount_cent BIGINT NOT NULL DEFAULT 0,
    result_status VARCHAR(32) NOT NULL DEFAULT 'MATCH',
    is_deleted TINYINT(1) NOT NULL DEFAULT 0,
    created_by BIGINT UNSIGNED NOT NULL DEFAULT 0,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_by BIGINT UNSIGNED NOT NULL DEFAULT 0,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    KEY idx_tenant_project_time (tenant_id, project_id, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS finance_lock_log (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    tenant_id BIGINT UNSIGNED NOT NULL,
    project_id BIGINT UNSIGNED NOT NULL,
    lock_status VARCHAR(32) NOT NULL,
    reason VARCHAR(500) DEFAULT NULL,
    is_deleted TINYINT(1) NOT NULL DEFAULT 0,
    created_by BIGINT UNSIGNED NOT NULL DEFAULT 0,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_by BIGINT UNSIGNED NOT NULL DEFAULT 0,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    KEY idx_tenant_project_status (tenant_id, project_id, lock_status),
    KEY idx_tenant_time (tenant_id, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT INTO permission (id, permission_code, permission_name, module)
VALUES
    (1046, 'finance.reconciliation', '财务对账', 'finance'),
    (1047, 'finance.lock', '财务锁账', 'finance'),
    (1048, 'finance.unlock', '财务解锁', 'finance')
ON DUPLICATE KEY UPDATE permission_name = VALUES(permission_name), module = VALUES(module);

INSERT INTO role_permission (id, tenant_id, role_id, permission_id)
VALUES
    (47, 1, 101, 1046),
    (48, 1, 101, 1047),
    (49, 1, 101, 1048)
ON DUPLICATE KEY UPDATE permission_id = VALUES(permission_id);
