-- Migration 055: Unified Audit Reports
-- Combines Social Media, GBP, and SEO audits into single reports
-- Date: 2026-02-06

CREATE TABLE IF NOT EXISTS audit_reports (
    id SERIAL PRIMARY KEY,
    company_id INTEGER REFERENCES companies(id) ON DELETE CASCADE,
    report_type VARCHAR(20) DEFAULT 'full', -- full, social, gbp, seo
    period_start DATE,
    period_end DATE,

    -- Overall scores
    overall_score INTEGER, -- 0-100 composite
    social_score INTEGER, -- 0-100
    gbp_score INTEGER, -- 0-100
    seo_score INTEGER, -- 0-100

    -- Report sections
    sections JSONB, -- {"social": true, "gbp": true, "seo": true, "competitors": true}

    -- Pre-rendered report data
    data JSONB, -- Full report payload

    -- Metadata
    custom_message TEXT,
    generated_by VARCHAR(50) DEFAULT 'system', -- system, admin, api
    generated_at TIMESTAMP DEFAULT NOW(),
    status VARCHAR(20) DEFAULT 'draft', -- draft, published

    created_at TIMESTAMP DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_audit_reports_company ON audit_reports(company_id);
CREATE INDEX IF NOT EXISTS idx_audit_reports_status ON audit_reports(status);
CREATE INDEX IF NOT EXISTS idx_audit_reports_date ON audit_reports(generated_at);

-- Permissions
GRANT ALL ON TABLE audit_reports TO nordabiz_app;
GRANT USAGE, SELECT ON SEQUENCE audit_reports_id_seq TO nordabiz_app;
