-- =============================================================================
-- Job Scheduler Tables — Oracle
-- =============================================================================
-- Auto-executed ketika JOB_ENABLED=true
-- Oracle tidak mendukung CREATE TABLE IF NOT EXISTS,
-- menggunakan PL/SQL block dengan pengecekan user_tables/user_indexes
-- Tipe data: VARCHAR2, NUMBER, TIMESTAMP, CLOB
-- =============================================================================

-- -----------------------------------------------------------------------------
-- Table: job_registry
-- Menyimpan definisi dan status terkini setiap job yang terdaftar
-- -----------------------------------------------------------------------------
DECLARE
    v_count NUMBER;
BEGIN
    SELECT COUNT(*) INTO v_count FROM user_tables WHERE table_name = 'JOB_REGISTRY';
    IF v_count = 0 THEN
        EXECUTE IMMEDIATE '
            CREATE TABLE job_registry (
                job_name            VARCHAR2(100)   NOT NULL,
                display_name        VARCHAR2(255),
                type                VARCHAR2(20)    DEFAULT ''cron'' NOT NULL,
                schedule            VARCHAR2(50),
                queue               VARCHAR2(20)    DEFAULT ''default'' NOT NULL,
                handler             VARCHAR2(255)   NOT NULL,
                config_file         VARCHAR2(255)   NOT NULL,
                timeout             NUMBER(10)      DEFAULT 30000 NOT NULL,
                retry_max           NUMBER(5)       DEFAULT 3 NOT NULL,
                retry_backoff       VARCHAR2(20)    DEFAULT ''exponential'' NOT NULL,
                status              VARCHAR2(20)    DEFAULT ''offline'' NOT NULL,
                last_run_at         TIMESTAMP,
                last_status         VARCHAR2(20),
                last_duration_ms    NUMBER(10),
                next_run_at         TIMESTAMP,
                total_success       NUMBER(10)      DEFAULT 0 NOT NULL,
                total_failed        NUMBER(10)      DEFAULT 0 NOT NULL,
                created_at          TIMESTAMP       DEFAULT SYSTIMESTAMP NOT NULL,
                updated_at          TIMESTAMP       DEFAULT SYSTIMESTAMP NOT NULL,
                CONSTRAINT pk_job_registry PRIMARY KEY (job_name)
            )';
    END IF;
END;
/

-- -----------------------------------------------------------------------------
-- Table: job_history
-- Menyimpan setiap record eksekusi job beserta hasilnya
-- -----------------------------------------------------------------------------
DECLARE
    v_count NUMBER;
BEGIN
    SELECT COUNT(*) INTO v_count FROM user_tables WHERE table_name = 'JOB_HISTORY';
    IF v_count = 0 THEN
        EXECUTE IMMEDIATE '
            CREATE TABLE job_history (
                id                  VARCHAR2(70)    NOT NULL,
                job_name            VARCHAR2(100)   NOT NULL,
                bullmq_job_id       VARCHAR2(100),
                trigger_type        VARCHAR2(20)    NOT NULL,
                triggered_by        VARCHAR2(100)   DEFAULT ''system'' NOT NULL,
                status              VARCHAR2(20)    NOT NULL,
                queue               VARCHAR2(20)    DEFAULT ''default'' NOT NULL,
                attempt             NUMBER(5)       DEFAULT 1 NOT NULL,
                config_file         VARCHAR2(255),
                started_at          TIMESTAMP       NOT NULL,
                completed_at        TIMESTAMP,
                duration_ms         NUMBER(10),
                progress            NUMBER(3),
                result_summary      VARCHAR2(500),
                error_message       VARCHAR2(1000),
                error_stack         CLOB,
                worker_pid          NUMBER(10),
                created_at          TIMESTAMP       DEFAULT SYSTIMESTAMP NOT NULL,
                CONSTRAINT pk_job_history PRIMARY KEY (id),
                CONSTRAINT fk_job_history_registry
                    FOREIGN KEY (job_name) REFERENCES job_registry(job_name)
            )';
    END IF;
END;
/

-- -----------------------------------------------------------------------------
-- Indexes untuk job_history
-- -----------------------------------------------------------------------------
DECLARE
    v_count NUMBER;
BEGIN
    SELECT COUNT(*) INTO v_count FROM user_indexes WHERE index_name = 'IDX_JOB_HISTORY_NAME_STARTED';
    IF v_count = 0 THEN
        EXECUTE IMMEDIATE 'CREATE INDEX idx_job_history_name_started ON job_history (job_name, started_at DESC)';
    END IF;

    SELECT COUNT(*) INTO v_count FROM user_indexes WHERE index_name = 'IDX_JOB_HISTORY_STATUS_STARTED';
    IF v_count = 0 THEN
        EXECUTE IMMEDIATE 'CREATE INDEX idx_job_history_status_started ON job_history (status, started_at DESC)';
    END IF;

    SELECT COUNT(*) INTO v_count FROM user_indexes WHERE index_name = 'IDX_JOB_HISTORY_STARTED';
    IF v_count = 0 THEN
        EXECUTE IMMEDIATE 'CREATE INDEX idx_job_history_started ON job_history (started_at DESC)';
    END IF;

    SELECT COUNT(*) INTO v_count FROM user_indexes WHERE index_name = 'IDX_JOB_HISTORY_BULLMQ_ID';
    IF v_count = 0 THEN
        EXECUTE IMMEDIATE 'CREATE INDEX idx_job_history_bullmq_id ON job_history (bullmq_job_id)';
    END IF;
END;
/
