CREATE EXTENSION IF NOT EXISTS pgcrypto;

CREATE TABLE IF NOT EXISTS desktop_bug_reports (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    report_type TEXT NOT NULL DEFAULT 'crash'
        CHECK (report_type IN ('crash', 'bug')),
    status TEXT NOT NULL DEFAULT 'new'
        CHECK (status IN ('new', 'triaged', 'in_progress', 'resolved', 'ignored')),
    severity TEXT NOT NULL DEFAULT 'medium'
        CHECK (severity IN ('low', 'medium', 'high', 'critical')),
    tenant_id BIGINT REFERENCES tenants(id) ON DELETE SET NULL,
    workspace_id BIGINT REFERENCES workspaces(id) ON DELETE SET NULL,
    user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
    desktop_client_id UUID REFERENCES desktop_clients(id) ON DELETE SET NULL,
    crash_guid TEXT,
    crash_report_id TEXT,
    process_type TEXT,
    electron_version TEXT,
    app_version TEXT,
    product_name TEXT,
    platform TEXT,
    os_arch TEXT,
    device_name TEXT,
    title TEXT NOT NULL,
    description TEXT,
    dump_object_key TEXT,
    dump_file_name TEXT,
    dump_size_bytes BIGINT,
    dump_sha256 TEXT,
    form_fields JSONB NOT NULL DEFAULT '{}'::jsonb,
    runtime_snapshot JSONB NOT NULL DEFAULT '{}'::jsonb,
    app_log_tail TEXT,
    resolution_note TEXT,
    uploader_ip TEXT,
    user_agent TEXT,
    occurred_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    resolved_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_desktop_bug_reports_created_at
    ON desktop_bug_reports (created_at DESC);

CREATE INDEX IF NOT EXISTS idx_desktop_bug_reports_status_created
    ON desktop_bug_reports (status, created_at DESC);

CREATE INDEX IF NOT EXISTS idx_desktop_bug_reports_severity_created
    ON desktop_bug_reports (severity, created_at DESC);

CREATE INDEX IF NOT EXISTS idx_desktop_bug_reports_client
    ON desktop_bug_reports (desktop_client_id, created_at DESC)
    WHERE desktop_client_id IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_desktop_bug_reports_workspace
    ON desktop_bug_reports (tenant_id, workspace_id, created_at DESC)
    WHERE tenant_id IS NOT NULL AND workspace_id IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_desktop_bug_reports_crash_guid
    ON desktop_bug_reports (crash_guid)
    WHERE crash_guid IS NOT NULL;
