-- =============================================================================
-- Migration 005: Company Profile Table
--
-- Dedicated table for company profiles with audit logging.
-- =============================================================================

CREATE TABLE IF NOT EXISTS compliance_company_profiles (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id VARCHAR(255) NOT NULL UNIQUE,

    -- Basic Info
    company_name VARCHAR(500) NOT NULL DEFAULT '',
    legal_form VARCHAR(50) DEFAULT 'GmbH',
    industry VARCHAR(255) DEFAULT '',
    founded_year INTEGER,

    -- Business Model
    business_model VARCHAR(20) DEFAULT 'B2B',
    offerings JSONB DEFAULT '[]'::jsonb,

    -- Size & Scope
    company_size VARCHAR(20) DEFAULT 'small',
    employee_count VARCHAR(20) DEFAULT '1-9',
    annual_revenue VARCHAR(50) DEFAULT '< 2 Mio',

    -- Locations
    headquarters_country VARCHAR(10) DEFAULT 'DE',
    headquarters_city VARCHAR(255) DEFAULT '',
    has_international_locations BOOLEAN DEFAULT FALSE,
    international_countries JSONB DEFAULT '[]'::jsonb,

    -- Target Markets & Legal Scope
    target_markets JSONB DEFAULT '["DE"]'::jsonb,
    primary_jurisdiction VARCHAR(10) DEFAULT 'DE',

    -- Data Processing Role
    is_data_controller BOOLEAN DEFAULT TRUE,
    is_data_processor BOOLEAN DEFAULT FALSE,

    -- AI Usage
    uses_ai BOOLEAN DEFAULT FALSE,
    ai_use_cases JSONB DEFAULT '[]'::jsonb,

    -- Contact Persons
    dpo_name VARCHAR(255),
    dpo_email VARCHAR(255),
    legal_contact_name VARCHAR(255),
    legal_contact_email VARCHAR(255),

    -- Machine Builder Profile (optional)
    machine_builder JSONB,

    -- Completion
    is_complete BOOLEAN DEFAULT FALSE,
    completed_at TIMESTAMPTZ,

    -- Timestamps
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_company_profiles_tenant ON compliance_company_profiles(tenant_id);

-- Audit log for company profile changes
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);
