
CREATE TABLE public.arc_inbound_emails (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  from_email TEXT,
  from_name TEXT,
  to_email TEXT,
  subject TEXT,
  body_text TEXT,
  body_html TEXT,
  attachment_urls JSONB NOT NULL DEFAULT '[]'::jsonb,
  ai_project_type TEXT,
  ai_title TEXT,
  ai_description TEXT,
  ai_property_address TEXT,
  ai_raw JSONB,
  status TEXT NOT NULL DEFAULT 'new' CHECK (status IN ('new','assigned','dismissed')),
  arc_application_id UUID REFERENCES public.arc_applications(id) ON DELETE SET NULL,
  association_id UUID REFERENCES public.associations(id) ON DELETE SET NULL,
  assigned_by UUID,
  assigned_at TIMESTAMPTZ,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

ALTER TABLE public.arc_inbound_emails ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Staff can view inbound ARC emails"
ON public.arc_inbound_emails FOR SELECT TO authenticated
USING (has_role(auth.uid(), 'admin'::app_role) OR has_role(auth.uid(), 'manager'::app_role));

CREATE POLICY "Staff can update inbound ARC emails"
ON public.arc_inbound_emails FOR UPDATE TO authenticated
USING (has_role(auth.uid(), 'admin'::app_role) OR has_role(auth.uid(), 'manager'::app_role));

CREATE POLICY "Staff can delete inbound ARC emails"
ON public.arc_inbound_emails FOR DELETE TO authenticated
USING (has_role(auth.uid(), 'admin'::app_role) OR has_role(auth.uid(), 'manager'::app_role));

CREATE TRIGGER trg_arc_inbound_emails_updated
BEFORE UPDATE ON public.arc_inbound_emails
FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column();

CREATE INDEX idx_arc_inbound_emails_status ON public.arc_inbound_emails(status, created_at DESC);
