-- ─── Audit Logs ───────────────────────────────────────────
CREATE TABLE IF NOT EXISTS audit_logs (
    id          CHAR(36) NOT NULL DEFAULT (UUID()),
    tenant_id   CHAR(36) NULL,
    user_id     CHAR(36) NULL,
    action      VARCHAR(100) NOT NULL,
    entity_type VARCHAR(50) NULL,
    entity_id   CHAR(36) NULL,
    old_data    JSON NULL,
    new_data    JSON NULL,
    ip_address  VARCHAR(45) NULL,
    user_agent  TEXT NULL,
    metadata    JSON NULL,
    created_at  DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    INDEX idx_audit_tenant  (tenant_id),
    INDEX idx_audit_action  (action),
    INDEX idx_audit_created (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ─── Risk Scores ──────────────────────────────────────────
CREATE TABLE IF NOT EXISTS risk_scores (
    id          CHAR(36) NOT NULL DEFAULT (UUID()),
    tenant_id   CHAR(36) NOT NULL,
    company_id  CHAR(36) NOT NULL,
    invoice_id  CHAR(36) NULL,
    risk_type   VARCHAR(50) NOT NULL,
    score       TINYINT UNSIGNED NOT NULL,
    reason      TEXT NOT NULL,
    is_resolved TINYINT(1) NOT NULL DEFAULT 0,
    resolved_by CHAR(36) NULL,
    resolved_at DATETIME NULL,
    created_at  DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    INDEX idx_risk_tenant     (tenant_id),
    INDEX idx_risk_unresolved (is_resolved),
    CONSTRAINT fk_risk_tenant   FOREIGN KEY (tenant_id)  REFERENCES tenants(id)   ON DELETE CASCADE,
    CONSTRAINT fk_risk_company  FOREIGN KEY (company_id) REFERENCES companies(id) ON DELETE CASCADE,
    CONSTRAINT fk_risk_invoice  FOREIGN KEY (invoice_id) REFERENCES invoices(id)  ON DELETE SET NULL,
    CONSTRAINT fk_risk_resolver FOREIGN KEY (resolved_by) REFERENCES users(id)    ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ─── Queue Jobs ───────────────────────────────────────────
CREATE TABLE IF NOT EXISTS queue_jobs (
    id           CHAR(36) NOT NULL DEFAULT (UUID()),
    type         VARCHAR(100) NOT NULL,
    payload      JSON NOT NULL,
    priority     INT NOT NULL DEFAULT 0,
    attempts     INT NOT NULL DEFAULT 0,
    max_attempts INT NOT NULL DEFAULT 3,
    status       ENUM('pending','processing','completed','failed','dead')
                 NOT NULL DEFAULT 'pending',
    error        TEXT NULL,
    locked_at    DATETIME NULL,
    locked_by    VARCHAR(100) NULL,
    scheduled_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    completed_at DATETIME NULL,
    created_at   DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    INDEX idx_queue_pending (status, priority DESC, scheduled_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ─── API Keys ─────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS api_keys (
    id           CHAR(36) NOT NULL DEFAULT (UUID()),
    tenant_id    CHAR(36) NOT NULL,
    user_id      CHAR(36) NOT NULL,
    name         VARCHAR(100) NOT NULL,
    public_key   VARCHAR(64) NOT NULL,
    secret_hash  VARCHAR(255) NOT NULL,
    permissions  JSON DEFAULT (JSON_ARRAY('invoices:read','invoices:upload')),
    last_used_at DATETIME NULL,
    is_active    TINYINT(1) NOT NULL DEFAULT 1,
    expires_at   DATETIME NULL,
    created_at   DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE KEY uq_api_public_key (public_key),
    CONSTRAINT fk_apikeys_tenant FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE,
    CONSTRAINT fk_apikeys_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
