
-- 1. Create public_form_submission_reports table
CREATE TABLE public.public_form_submission_reports (
  id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  submission_id UUID NOT NULL REFERENCES public.public_form_submissions(id) ON DELETE CASCADE,
  template_id UUID NOT NULL REFERENCES public.public_form_templates(id) ON DELETE CASCADE,
  association_id UUID NOT NULL REFERENCES public.associations(id) ON DELETE CASCADE,
  report_data JSONB,
  status TEXT NOT NULL DEFAULT 'generated',
  generated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
  created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
  updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now()
);

-- Enable RLS
ALTER TABLE public.public_form_submission_reports ENABLE ROW LEVEL SECURITY;

-- Staff can manage reports
CREATE POLICY "Staff can manage submission reports"
  ON public.public_form_submission_reports
  FOR ALL
  TO authenticated
  USING (has_role(auth.uid(), 'admin') OR has_role(auth.uid(), 'manager'))
  WITH CHECK (has_role(auth.uid(), 'admin') OR has_role(auth.uid(), 'manager'));

-- 2. Add report_styling column to public_form_templates if missing
ALTER TABLE public.public_form_templates ADD COLUMN IF NOT EXISTS report_styling JSONB;

-- 3. Fix shared_links: ensure share_token has a default so INSERT works
ALTER TABLE public.shared_links ALTER COLUMN share_token SET DEFAULT encode(gen_random_bytes(16), 'hex');

-- 4. Fix the documents anon policy - it's too permissive (allows reading ALL documents)
-- Replace with a scoped policy that only allows reading documents referenced by a public shared link
DROP POLICY IF EXISTS "Anon can read documents via shared links" ON public.documents;

CREATE POLICY "Anon can read documents via shared links"
  ON public.documents
  FOR SELECT
  TO anon
  USING (
    id IN (
      SELECT sl.document_id FROM public.shared_links sl WHERE sl.is_public = true AND sl.document_id IS NOT NULL
    )
    OR
    category IN (
      SELECT sl.folder_name FROM public.shared_links sl WHERE sl.is_public = true AND sl.share_type = 'folder'
    )
  );

-- 5. Add employee/staff roles to shared_links policy so non-admin staff can create share links
DROP POLICY IF EXISTS "Staff full access on shared_links" ON public.shared_links;

CREATE POLICY "Staff full access on shared_links"
  ON public.shared_links
  FOR ALL
  TO authenticated
  USING (has_role(auth.uid(), 'admin') OR has_role(auth.uid(), 'manager') OR has_role(auth.uid(), 'employee') OR has_role(auth.uid(), 'staff'))
  WITH CHECK (has_role(auth.uid(), 'admin') OR has_role(auth.uid(), 'manager') OR has_role(auth.uid(), 'employee') OR has_role(auth.uid(), 'staff'));

-- Trigger for updated_at
CREATE TRIGGER update_public_form_submission_reports_updated_at
  BEFORE UPDATE ON public.public_form_submission_reports
  FOR EACH ROW
  EXECUTE FUNCTION public.update_updated_at_column();
