-- ============================================
-- WhatsApp Configuration per Tenant
-- ============================================

CREATE TABLE whatsapp.configs (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id UUID NOT NULL REFERENCES tenants.tenants(id) ON DELETE CASCADE,

  -- Meta Cloud API credentials
  phone_number_id VARCHAR(50) NOT NULL,
  business_account_id VARCHAR(50) NOT NULL,
  access_token TEXT NOT NULL, -- Encrypted

  -- Webhook configuration
  webhook_verify_token VARCHAR(100),
  webhook_secret VARCHAR(255),

  -- Configuration
  display_phone_number VARCHAR(20),
  verified_name VARCHAR(255),
  quality_rating VARCHAR(50),

  -- Status
  is_active BOOLEAN DEFAULT true,
  is_verified BOOLEAN DEFAULT false,
  last_verified_at TIMESTAMPTZ,

  -- Rate limiting
  daily_message_limit INTEGER DEFAULT 1000,
  messages_sent_today INTEGER DEFAULT 0,
  last_message_at TIMESTAMPTZ,

  -- Metadata
  metadata JSONB DEFAULT '{}',
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW(),

  UNIQUE(tenant_id)
);

-- Indexes
CREATE INDEX idx_whatsapp_configs_tenant ON whatsapp.configs(tenant_id);
CREATE INDEX idx_whatsapp_configs_phone ON whatsapp.configs(phone_number_id);
CREATE INDEX idx_whatsapp_configs_active ON whatsapp.configs(is_active) WHERE is_active = true;

-- RLS
ALTER TABLE whatsapp.configs ENABLE ROW LEVEL SECURITY;

CREATE POLICY whatsapp_configs_tenant_isolation ON whatsapp.configs
  USING (tenant_id = current_setting('app.current_tenant_id', true)::uuid);

-- Trigger for updated_at
CREATE TRIGGER update_whatsapp_configs_updated_at
  BEFORE UPDATE ON whatsapp.configs
  FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

-- Comments
COMMENT ON TABLE whatsapp.configs IS 'WhatsApp Business API configuration per tenant';
COMMENT ON COLUMN whatsapp.configs.access_token IS 'Encrypted Meta Cloud API access token';
COMMENT ON COLUMN whatsapp.configs.quality_rating IS 'GREEN, YELLOW, or RED quality rating from Meta';
