-- Migration 151: Reconcile opportunity comment attachments schema with migration 019 expectations
-- Some environments already had pipeline_opportunity_comment_attachments with legacy columns,
-- so migration 019 (CREATE TABLE IF NOT EXISTS) did not add these fields.

ALTER TABLE IF EXISTS pipeline_opportunity_comment_attachments
    ADD COLUMN IF NOT EXISTS content_type VARCHAR(100),
    ADD COLUMN IF NOT EXISTS stored_name TEXT,
    ADD COLUMN IF NOT EXISTS uploaded_by_user_id INTEGER;

DO $$
BEGIN
    IF EXISTS (
        SELECT 1
        FROM information_schema.columns
        WHERE table_schema = 'public'
          AND table_name = 'pipeline_opportunity_comment_attachments'
          AND column_name = 'file_path'
    ) THEN
        UPDATE pipeline_opportunity_comment_attachments
        SET stored_name = COALESCE(stored_name, file_path)
        WHERE stored_name IS NULL;
    END IF;

    IF EXISTS (
        SELECT 1
        FROM information_schema.columns
        WHERE table_schema = 'public'
          AND table_name = 'pipeline_opportunity_comment_attachments'
          AND column_name = 'file_type'
    ) THEN
        UPDATE pipeline_opportunity_comment_attachments
        SET content_type = COALESCE(content_type, file_type)
        WHERE content_type IS NULL;
    END IF;
END
$$;

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'pipeline_opportunity_comment_attachments_uploaded_by_fkey'
    ) THEN
        ALTER TABLE pipeline_opportunity_comment_attachments
        ADD CONSTRAINT pipeline_opportunity_comment_attachments_uploaded_by_fkey
        FOREIGN KEY (uploaded_by_user_id)
        REFERENCES users(user_id)
        ON DELETE SET NULL;
    END IF;
END
$$;

-- Keep existing rows valid while allowing future inserts to set explicit stored_name.
UPDATE pipeline_opportunity_comment_attachments
SET stored_name = COALESCE(stored_name, filename)
WHERE stored_name IS NULL;
