-- Migration 056: Add UDF storage + missing fields to companies table

ALTER TABLE companies
  ADD COLUMN IF NOT EXISTS user_defined_fields   JSONB,
  ADD COLUMN IF NOT EXISTS parent_company_id     BIGINT,
  ADD COLUMN IF NOT EXISTS web_address           VARCHAR(255),
  ADD COLUMN IF NOT EXISTS create_date           TIMESTAMP WITHOUT TIME ZONE,
  ADD COLUMN IF NOT EXISTS company_category_id   INTEGER,
  ADD COLUMN IF NOT EXISTS is_client_portal_active BOOLEAN DEFAULT false,
  ADD COLUMN IF NOT EXISTS is_task_fire_active   BOOLEAN DEFAULT false,
  ADD COLUMN IF NOT EXISTS is_comanaged          BOOLEAN DEFAULT false,
  ADD COLUMN IF NOT EXISTS country_id            INTEGER,
  ADD COLUMN IF NOT EXISTS bill_to_country_id    INTEGER,
  ADD COLUMN IF NOT EXISTS bill_to_address_to_use INTEGER,
  ADD COLUMN IF NOT EXISTS invoice_email_message_id BIGINT,
  ADD COLUMN IF NOT EXISTS purchase_order_template_id BIGINT,
  ADD COLUMN IF NOT EXISTS additional_address_information TEXT,
  ADD COLUMN IF NOT EXISTS bill_to_additional_address_info TEXT,
  ADD COLUMN IF NOT EXISTS bill_to_attention     VARCHAR(255),
  ADD COLUMN IF NOT EXISTS sic_code              VARCHAR(50),
  ADD COLUMN IF NOT EXISTS stock_market          VARCHAR(100),
  ADD COLUMN IF NOT EXISTS stock_symbol          VARCHAR(50),
  ADD COLUMN IF NOT EXISTS alternate_phone1      VARCHAR(50),
  ADD COLUMN IF NOT EXISTS alternate_phone2      VARCHAR(50),
  ADD COLUMN IF NOT EXISTS survey_company_rating INTEGER,
  ADD COLUMN IF NOT EXISTS asset_value           NUMERIC(18,4),
  ADD COLUMN IF NOT EXISTS created_by_resource_id BIGINT;

-- Index for UDF queries (e.g. find by PassportalID, MimecastID)
CREATE INDEX IF NOT EXISTS idx_companies_udfs ON companies USING gin(user_defined_fields);
CREATE INDEX IF NOT EXISTS idx_companies_parent ON companies(parent_company_id) WHERE parent_company_id IS NOT NULL;
