{"-- Add status column to form_submissions for tracking manager-controlled status
ALTER TABLE public.form_submissions
ADD COLUMN IF NOT EXISTS status text NOT NULL DEFAULT 'in_progress'","-- RLS: Allow organization admins and managers to update submissions in their organization
DO $$ BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_policies WHERE schemaname = 'public' AND tablename = 'form_submissions' AND policyname = 'Org admins/managers can update submissions' 
  ) THEN
    CREATE POLICY \"Org admins/managers can update submissions\"
    ON public.form_submissions
    FOR UPDATE
    USING (
      EXISTS (
        SELECT 1
        FROM public.form_assignments fa
        JOIN public.user_roles ur ON ur.organization_id = fa.organization_id
        WHERE fa.id = form_submissions.form_assignment_id
          AND ur.user_id = auth.uid()
          AND ur.role = ANY (ARRAY['admin'::user_role, 'manager'::user_role])
      )
    )
    WITH CHECK (
      EXISTS (
        SELECT 1
        FROM public.form_assignments fa
        JOIN public.user_roles ur ON ur.organization_id = fa.organization_id
        WHERE fa.id = form_submissions.form_assignment_id
          AND ur.user_id = auth.uid()
          AND ur.role = ANY (ARRAY['admin'::user_role, 'manager'::user_role])
      )
    );
  END IF;
END $$","-- RLS: Allow branch managers to update submissions they can view
DO $$ BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_policies WHERE schemaname = 'public' AND tablename = 'form_submissions' AND policyname = 'Branch managers can update branch form submissions' 
  ) THEN
    CREATE POLICY \"Branch managers can update branch form submissions\"
    ON public.form_submissions
    FOR UPDATE
    USING (branch_manager_can_view_submission(id))
    WITH CHECK (branch_manager_can_view_submission(id));
  END IF;
END $$"}