-- Report Generator plugin initial migration: creates report_templates and report_instances tables
CREATE TABLE IF NOT EXISTS report_templates (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(255) NOT NULL,
    description TEXT NOT NULL DEFAULT '',
    template_type VARCHAR(50) NOT NULL DEFAULT 'jinja2',
    content TEXT NOT NULL,
    output_format VARCHAR(50) NOT NULL DEFAULT 'csv',
    tenant_id UUID NOT NULL,
    created_by UUID NOT NULL,
    deleted_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS ix_report_templates_tenant ON report_templates(tenant_id);
CREATE INDEX IF NOT EXISTS ix_report_templates_name ON report_templates(name);

CREATE TABLE IF NOT EXISTS report_instances (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    template_id UUID NOT NULL REFERENCES report_templates(id) ON DELETE CASCADE,
    status VARCHAR(50) NOT NULL DEFAULT 'pending',
    output_path VARCHAR(1024),
    error_message TEXT,
    tenant_id UUID NOT NULL,
    created_by UUID NOT NULL,
    deleted_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS ix_report_instances_tenant ON report_instances(tenant_id);
CREATE INDEX IF NOT EXISTS ix_report_instances_template ON report_instances(template_id);
CREATE INDEX IF NOT EXISTS ix_report_instances_status ON report_instances(status);
