/*
 * -------------------------------------------------------
 * Shared Communications Table for Courses, Events, Bookings
 * Tracks email, phone, letter, meeting, note, sms entries
 * -------------------------------------------------------
 */

CREATE TABLE IF NOT EXISTS public.module_communications (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  account_id uuid NOT NULL REFERENCES public.accounts(id) ON DELETE CASCADE,
  module text NOT NULL CHECK (module IN ('courses', 'events', 'bookings')),
  entity_id uuid NOT NULL,
  type text NOT NULL DEFAULT 'note' CHECK (type IN ('email', 'phone', 'letter', 'meeting', 'note', 'sms')),
  direction text NOT NULL DEFAULT 'internal' CHECK (direction IN ('inbound', 'outbound', 'internal')),
  subject text,
  body text,
  email_to text,
  email_cc text,
  attachment_paths text[],
  created_by uuid REFERENCES auth.users(id) ON DELETE SET NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS ix_module_communications_entity
  ON public.module_communications(module, entity_id, created_at DESC);

CREATE INDEX IF NOT EXISTS ix_module_communications_account
  ON public.module_communications(account_id, module, created_at DESC);

ALTER TABLE public.module_communications ENABLE ROW LEVEL SECURITY;
REVOKE ALL ON public.module_communications FROM authenticated, service_role;
GRANT SELECT, INSERT, UPDATE, DELETE ON public.module_communications TO authenticated;
GRANT ALL ON public.module_communications TO service_role;

CREATE POLICY module_communications_select ON public.module_communications
  FOR SELECT TO authenticated USING (public.has_role_on_account(account_id));

CREATE POLICY module_communications_mutate ON public.module_communications
  FOR ALL TO authenticated USING (public.has_role_on_account(account_id))
  WITH CHECK (public.has_role_on_account(account_id));
