-- Migration 002: Task #7 — Multi-WABA per Service + Sender-Level Client Dedication
-- Allows multiple WABA credentials per service; senders can be dedicated to specific clients

-- 1. Add `name` field to infobip_configs (required, default "WABA Principal")
ALTER TABLE infobip_configs
  ADD COLUMN IF NOT EXISTS name VARCHAR(255) NOT NULL DEFAULT 'WABA Principal';

-- 2. Remove UNIQUE constraint on service_id in infobip_configs (allows multiple WABAs per service)
--    Drop only if it exists (idempotent)
DO $$
BEGIN
  IF EXISTS (
    SELECT 1 FROM pg_constraint
    WHERE conname = 'infobip_configs_service_id_key'
      AND conrelid = 'infobip_configs'::regclass
  ) THEN
    ALTER TABLE infobip_configs DROP CONSTRAINT infobip_configs_service_id_key;
  END IF;
END $$;

-- 3. Add `config_id` FK to infobip_senders (links sender to its WABA config)
ALTER TABLE infobip_senders
  ADD COLUMN IF NOT EXISTS config_id VARCHAR(255) REFERENCES infobip_configs(id) ON DELETE CASCADE;

-- 4. Add `dedicated_to_user_id` FK to infobip_senders (NULL = pool; set = dedicated client sender)
ALTER TABLE infobip_senders
  ADD COLUMN IF NOT EXISTS dedicated_to_user_id VARCHAR(255) REFERENCES users(id) ON DELETE SET NULL;
