-- Migration 042: Add project_id to compliance_company_profiles
-- Enables multi-project company profiles (one profile per tenant+project)
--
-- Previously: UNIQUE(tenant_id) — only one profile per tenant
-- Now: UNIQUE(tenant_id, project_id) — one profile per tenant+project

BEGIN;

-- 1. Add project_id column (nullable for backwards compat with existing rows)
ALTER TABLE compliance_company_profiles
    ADD COLUMN IF NOT EXISTS project_id UUID;

-- 2. Add offering_urls column (was in frontend but missing in DB)
ALTER TABLE compliance_company_profiles
    ADD COLUMN IF NOT EXISTS offering_urls JSONB DEFAULT '{}'::jsonb;

-- 3. Add address columns (were in frontend but missing in DB)
ALTER TABLE compliance_company_profiles
    ADD COLUMN IF NOT EXISTS headquarters_country_other VARCHAR(255) DEFAULT '',
    ADD COLUMN IF NOT EXISTS headquarters_street VARCHAR(500) DEFAULT '',
    ADD COLUMN IF NOT EXISTS headquarters_zip VARCHAR(20) DEFAULT '',
    ADD COLUMN IF NOT EXISTS headquarters_state VARCHAR(255) DEFAULT '';

-- 4. Drop old UNIQUE constraint on tenant_id alone
DO $$
BEGIN
    -- The constraint might be named differently depending on how it was created
    IF EXISTS (
        SELECT 1 FROM pg_constraint
        WHERE conname = 'compliance_company_profiles_tenant_id_key'
    ) THEN
        ALTER TABLE compliance_company_profiles
            DROP CONSTRAINT compliance_company_profiles_tenant_id_key;
    END IF;
END $$;

-- 5. Create new UNIQUE constraint on (tenant_id, project_id)
-- Using COALESCE to handle NULL project_id (legacy rows)
CREATE UNIQUE INDEX IF NOT EXISTS idx_company_profiles_tenant_project
    ON compliance_company_profiles (tenant_id, COALESCE(project_id, '00000000-0000-0000-0000-000000000000'::uuid));

-- 6. Add FK to compliance_projects (if the referenced table exists)
DO $$
BEGIN
    IF EXISTS (
        SELECT 1 FROM information_schema.tables
        WHERE table_name = 'compliance_projects'
    ) THEN
        -- Only add FK if not already present
        IF NOT EXISTS (
            SELECT 1 FROM pg_constraint
            WHERE conname = 'fk_company_profiles_project'
        ) THEN
            ALTER TABLE compliance_company_profiles
                ADD CONSTRAINT fk_company_profiles_project
                FOREIGN KEY (project_id) REFERENCES compliance_projects(id)
                ON DELETE CASCADE;
        END IF;
    END IF;
END $$;

-- 7. Create audit table if not exists, then add project_id
CREATE TABLE IF NOT EXISTS compliance_company_profile_audit (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id VARCHAR(255) NOT NULL,
    action VARCHAR(20) NOT NULL,
    changed_fields JSONB,
    changed_by VARCHAR(255),
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_company_profile_audit_tenant ON compliance_company_profile_audit(tenant_id);

ALTER TABLE compliance_company_profile_audit
    ADD COLUMN IF NOT EXISTS project_id UUID;

COMMIT;
