DROP TABLE IF EXISTS public.yuntu_report_info;

CREATE TABLE public.yuntu_report_info (
    id BIGSERIAL PRIMARY KEY,
    report_id VARCHAR(64) NOT NULL,
    source_type VARCHAR(32) NOT NULL,
    source_report_id VARCHAR(64) NULL,
    aadvid VARCHAR(32) NOT NULL,
    name TEXT NOT NULL,
    price JSONB NOT NULL DEFAULT '[]'::jsonb,
    rules JSONB NOT NULL DEFAULT '[]'::jsonb,
    analysis_dims JSONB NOT NULL DEFAULT '[]'::jsonb,
    categories JSONB NOT NULL DEFAULT '[]'::jsonb,
    transaction_channels JSONB NOT NULL DEFAULT '[]'::jsonb,
    start_time DATE NOT NULL,
    end_time DATE NOT NULL,
    period_type VARCHAR(32) NULL,
    user_name TEXT NULL,
    payload JSONB NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CONSTRAINT uq_yuntu_report_info_report_id UNIQUE (report_id),
    CONSTRAINT chk_yuntu_report_info_source_type
        CHECK (source_type IN ('MANUAL_CAPTURE', 'AUTO_COPY')),
    CONSTRAINT chk_yuntu_report_info_copy_source
        CHECK (
            (source_type = 'MANUAL_CAPTURE' AND source_report_id IS NULL)
            OR
            (source_type = 'AUTO_COPY' AND source_report_id IS NOT NULL)
        )
);

CREATE INDEX idx_yuntu_report_info_source_report_id
    ON public.yuntu_report_info (source_report_id);

CREATE INDEX idx_yuntu_report_info_created_at
    ON public.yuntu_report_info (created_at DESC);

CREATE INDEX idx_yuntu_report_info_aadvid_created_at
    ON public.yuntu_report_info (aadvid, created_at DESC);

CREATE OR REPLACE FUNCTION public.set_yuntu_report_info_updated_at()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = NOW();
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS trg_yuntu_report_info_updated_at ON public.yuntu_report_info;

CREATE TRIGGER trg_yuntu_report_info_updated_at
BEFORE UPDATE ON public.yuntu_report_info
FOR EACH ROW
EXECUTE FUNCTION public.set_yuntu_report_info_updated_at();
