ALTER TABLE internet_connections_connections
ADD COLUMN IF NOT EXISTS allocation_model VARCHAR(20) NOT NULL DEFAULT 'dedicated',
ADD COLUMN IF NOT EXISTS value_type VARCHAR(30) NOT NULL DEFAULT 'other',
ADD COLUMN IF NOT EXISTS value_label VARCHAR(120),
ADD COLUMN IF NOT EXISTS subscription_id INTEGER REFERENCES sag_subscriptions(id) ON DELETE SET NULL;

UPDATE internet_connections_connections
SET allocation_model = 'shared',
    value_type = 'bmc_networks',
    value_label = NULL,
    updated_at = CURRENT_TIMESTAMP
WHERE deleted_at IS NULL
  AND customer_id IN (
      SELECT id
      FROM customers
      WHERE is_active = true
        AND LOWER(name) = 'bmc networks'
  );

UPDATE internet_connections_connections
SET allocation_model = COALESCE(NULLIF(allocation_model, ''), 'dedicated'),
    value_type = CASE
        WHEN value_type IN ('subscription', 'bmc_networks', 'delefiber', 'other') THEN value_type
        ELSE 'other'
    END,
    value_label = CASE
        WHEN value_type = 'other' AND COALESCE(NULLIF(TRIM(value_label), ''), '') = '' THEN 'Mangler klassifikation'
        WHEN value_type IN ('bmc_networks', 'delefiber', 'subscription') THEN NULL
        ELSE value_label
    END,
    updated_at = CURRENT_TIMESTAMP
WHERE deleted_at IS NULL
  AND NOT (
      allocation_model = 'shared'
      AND value_type = 'bmc_networks'
      AND customer_id IN (
          SELECT id
          FROM customers
          WHERE is_active = true
            AND LOWER(name) = 'bmc networks'
      )
  );

CREATE INDEX IF NOT EXISTS idx_internet_connections_allocation_model
ON internet_connections_connections(allocation_model);

CREATE INDEX IF NOT EXISTS idx_internet_connections_value_type
ON internet_connections_connections(value_type);

CREATE INDEX IF NOT EXISTS idx_internet_connections_subscription_id
ON internet_connections_connections(subscription_id)
WHERE subscription_id IS NOT NULL;
