-- ============================================================
-- SECURITY DEFINER RPCs for toggling IT Job printed status.
-- The tasks table RLS UPDATE policies restrict who can update
-- rows, but dispatchers/admins need to set it_job_printed
-- regardless of task ownership. SECURITY DEFINER bypasses RLS
-- while still validating the caller's role.
-- ============================================================

CREATE OR REPLACE FUNCTION public.mark_it_job_printed(
  p_task_id   uuid,
  p_receiver_id uuid
)
RETURNS void
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM profiles
    WHERE id = auth.uid()
      AND role IN ('admin', 'dispatcher', 'programmer')
  ) THEN
    RAISE EXCEPTION 'Only admin or dispatcher can mark IT Job as received';
  END IF;

  UPDATE tasks
  SET it_job_printed        = true,
      it_job_printed_at     = now(),
      it_job_received_by_id = p_receiver_id
  WHERE id = p_task_id;
END;
$$;

CREATE OR REPLACE FUNCTION public.unmark_it_job_printed(
  p_task_id uuid
)
RETURNS void
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM profiles
    WHERE id = auth.uid()
      AND role IN ('admin', 'dispatcher', 'programmer')
  ) THEN
    RAISE EXCEPTION 'Only admin or dispatcher can unmark IT Job as received';
  END IF;

  UPDATE tasks
  SET it_job_printed        = false,
      it_job_printed_at     = null,
      it_job_received_by_id = null
  WHERE id = p_task_id;
END;
$$;
