-- Add justification column to attendance_logs for overtime check-ins
ALTER TABLE attendance_logs ADD COLUMN IF NOT EXISTS justification text;

-- Overtime check-in RPC: creates overtime duty_schedule + attendance_log in one call.
-- Returns the attendance log ID.
CREATE OR REPLACE FUNCTION public.overtime_check_in(
  p_lat double precision,
  p_lng double precision,
  p_justification text DEFAULT NULL
) 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;

  -- Overtime shift: start now, end after 8 hours (can be checked out earlier)
  v_end_time := v_now + interval '8 hours';

  -- Create overtime duty schedule
  INSERT INTO duty_schedules (user_id, shift_type, start_time, end_time, status, check_in_at, check_in_location)
  VALUES (
    v_uid,
    -- Store as a normal shift_type to satisfy enum constraints;
    -- overtime semantics are captured by this RPC + log justification.
    'normal',
    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;

  -- Create attendance log
  INSERT INTO attendance_logs (user_id, duty_schedule_id, check_in_at, check_in_lat, check_in_lng, justification)
  VALUES (v_uid, v_schedule_id, v_now, p_lat, p_lng, p_justification)
  RETURNING id INTO v_log_id;

  RETURN v_log_id;
END;
$$;
