-- Ensure there is only one overload of attendance_check_out.
--
-- Having both the 3-parameter and 4-parameter overloads causes PostgREST to
-- return "could not choose best candidate function" when calling the RPC with
-- only the required parameters.

DROP FUNCTION IF EXISTS public.attendance_check_out(uuid, double precision, double precision);

-- Ensure the 4-parameter version (with optional justification) exists.
CREATE OR REPLACE FUNCTION public.attendance_check_out(
  p_attendance_id uuid,
  p_lat double precision,
  p_lng double precision,
  p_justification text DEFAULT NULL
) RETURNS void
LANGUAGE plpgsql SECURITY DEFINER
AS $$
DECLARE
  v_log attendance_logs%ROWTYPE;
BEGIN
  SELECT * INTO v_log FROM attendance_logs WHERE id = p_attendance_id;
  IF NOT FOUND THEN
    RAISE EXCEPTION 'Attendance log not found';
  END IF;
  IF v_log.user_id != auth.uid() THEN
    RAISE EXCEPTION 'Not your attendance log';
  END IF;
  IF v_log.check_out_at IS NOT NULL THEN
    RAISE EXCEPTION 'Already checked out';
  END IF;

  UPDATE attendance_logs
  SET check_out_at = now(),
      check_out_lat = p_lat,
      check_out_lng = p_lng,
      check_out_justification = p_justification
  WHERE id = p_attendance_id;
END;
$$;
