-- Fix: drop the old 3-parameter overload of attendance_check_out.
-- The migration 20260308160000 added a 4-parameter version (with p_justification DEFAULT NULL)
-- but CREATE OR REPLACE does not replace a function with a different signature —
-- it created a second overload instead. When called with 3 args both overloads match,
-- causing "Could not choose the best candidate function".

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

-- Re-ensure the 4-parameter version exists (idempotent).
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;
$$;
