
-- Add void tracking columns
ALTER TABLE public.signature_envelopes
  ADD COLUMN IF NOT EXISTS voided_at timestamptz,
  ADD COLUMN IF NOT EXISTS voided_reason text,
  ADD COLUMN IF NOT EXISTS voided_by uuid;

-- Signature field placements
CREATE TABLE IF NOT EXISTS public.signature_fields (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  envelope_id uuid NOT NULL REFERENCES public.signature_envelopes(id) ON DELETE CASCADE,
  recipient_id uuid NOT NULL REFERENCES public.signature_recipients(id) ON DELETE CASCADE,
  field_type text NOT NULL CHECK (field_type IN ('signature', 'date', 'name', 'initials')),
  page_number integer NOT NULL DEFAULT 1,
  x_ratio numeric NOT NULL,            -- 0..1 from left
  y_ratio numeric NOT NULL,            -- 0..1 from top (UI coord)
  width_ratio numeric NOT NULL DEFAULT 0.20,
  height_ratio numeric NOT NULL DEFAULT 0.05,
  required boolean NOT NULL DEFAULT true,
  created_at timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_signature_fields_envelope ON public.signature_fields(envelope_id);
CREATE INDEX IF NOT EXISTS idx_signature_fields_recipient ON public.signature_fields(recipient_id);

ALTER TABLE public.signature_fields ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Staff manage signature fields"
  ON public.signature_fields
  FOR ALL
  TO authenticated
  USING (public.has_role(auth.uid(), 'admin'::public.app_role) OR public.has_role(auth.uid(), 'manager'::public.app_role))
  WITH CHECK (public.has_role(auth.uid(), 'admin'::public.app_role) OR public.has_role(auth.uid(), 'manager'::public.app_role));

CREATE POLICY "Recipients view their fields"
  ON public.signature_fields
  FOR SELECT
  USING (EXISTS (
    SELECT 1 FROM public.signature_recipients r
    WHERE r.id = signature_fields.recipient_id
      AND (r.user_id = auth.uid() OR lower(r.email) = lower(auth.email()))
  ));
