-- ============================================
-- WhatsApp Message Log
-- ============================================
-- Note: ENUMs are defined in 02-enums.sql

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

  -- Message identifiers
  wamid VARCHAR(100), -- WhatsApp Message ID from Meta
  conversation_id VARCHAR(100),

  -- Direction and type
  direction whatsapp.message_direction NOT NULL DEFAULT 'outbound',
  message_type whatsapp.message_type NOT NULL DEFAULT 'text',

  -- Recipient/Sender
  phone_number VARCHAR(20) NOT NULL, -- E.164 format
  user_id UUID REFERENCES users.users(id) ON DELETE SET NULL,
  contact_name VARCHAR(255),

  -- Content
  content TEXT,
  template_name VARCHAR(100),
  template_language VARCHAR(10) DEFAULT 'es',
  template_components JSONB,
  media_url TEXT,
  media_mime_type VARCHAR(100),

  -- Status tracking
  status whatsapp.message_status DEFAULT 'pending',
  status_timestamp TIMESTAMPTZ,
  error_code VARCHAR(50),
  error_message TEXT,

  -- Pricing
  pricing_model VARCHAR(50),
  pricing_category VARCHAR(50),

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

-- Indexes
CREATE INDEX idx_whatsapp_messages_tenant ON whatsapp.messages(tenant_id);
CREATE INDEX idx_whatsapp_messages_config ON whatsapp.messages(config_id);
CREATE INDEX idx_whatsapp_messages_wamid ON whatsapp.messages(wamid);
CREATE INDEX idx_whatsapp_messages_phone ON whatsapp.messages(phone_number);
CREATE INDEX idx_whatsapp_messages_user ON whatsapp.messages(user_id);
CREATE INDEX idx_whatsapp_messages_status ON whatsapp.messages(status);
CREATE INDEX idx_whatsapp_messages_created ON whatsapp.messages(created_at DESC);
CREATE INDEX idx_whatsapp_messages_direction ON whatsapp.messages(direction);

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

CREATE POLICY whatsapp_messages_tenant_isolation ON whatsapp.messages
  USING (tenant_id = current_setting('app.current_tenant_id')::uuid);

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

-- Comments
COMMENT ON TABLE whatsapp.messages IS 'WhatsApp message history for both inbound and outbound messages';
COMMENT ON COLUMN whatsapp.messages.wamid IS 'WhatsApp Message ID returned by Meta API';
COMMENT ON COLUMN whatsapp.messages.phone_number IS 'Phone number in E.164 format (e.g., +521234567890)';
