-- Fix overtime_check_in to accept p_accuracy and p_is_mocked.
-- Migration 20260504000000 added these to attendance_check_in/out but missed
-- overtime_check_in, causing a PostgREST "no candidate" error during overtime
-- check-in when Flutter passes these two params.
--
-- The attendance_logs columns check_in_accuracy and check_in_is_mocked already
-- exist (added in 20260504000000), so only the function signature needs updating.

CREATE OR REPLACE FUNCTION public.overtime_check_in(
  p_lat           double precision,
  p_lng           double precision,
  p_justification text             DEFAULT NULL,
  p_accuracy      double precision DEFAULT NULL,
  p_is_mocked     boolean          DEFAULT false
) RETURNS uuid
LANGUAGE plpgsql SECURITY DEFINER
AS $$
DECLARE
  v_uid         uuid        := auth.uid();
  v_now         timestamptz := now();
  v_schedule_id uuid;
  v_log_id      uuid;
  v_end_time    timestamptz;
BEGIN
  IF v_uid IS NULL THEN
    RAISE EXCEPTION 'Not authenticated';
  END IF;

  v_end_time := v_now + interval '8 hours';

  INSERT INTO duty_schedules (
    user_id, shift_type, start_time, end_time,
    status, check_in_at, check_in_location
  )
  VALUES (
    v_uid, 'overtime', v_now, v_end_time,
    'arrival'::duty_status, v_now,
    ST_SetSRID(ST_MakePoint(p_lng, p_lat), 4326)::geography
  )
  RETURNING id INTO v_schedule_id;

  INSERT INTO attendance_logs (
    user_id, duty_schedule_id, check_in_at,
    check_in_lat, check_in_lng,
    justification, check_in_accuracy, check_in_is_mocked
  )
  VALUES (
    v_uid, v_schedule_id, v_now,
    p_lat, p_lng,
    p_justification, p_accuracy, p_is_mocked
  )
  RETURNING id INTO v_log_id;

  RETURN v_log_id;
END;
$$;

-- Drop the old 3-param attendance_check_in overload (from 20260307090000).
-- The 5-param version (with p_accuracy, p_is_mocked) is the only correct one.
-- Mirrors the cleanup done for attendance_check_out in 20260309090000.
DROP FUNCTION IF EXISTS public.attendance_check_in(uuid, double precision, double precision);
