-- ============================================================================
-- 0094_time_tracking_one_open_clock_in.sql
--
-- Cycle 2 of the water-log/time-tracking refactor. A field worker must not
-- have two open clock-ins at once — concurrent requests, offline retries,
-- and double-taps on a slow phone all create the same hazard. A partial
-- unique index on (worker_id) WHERE clock_out IS NULL is the only DB-level
-- guard, since READ COMMITTED transactions can both pass an
-- "is there an open log?" SELECT before either INSERT commits.
--
-- The application catches the unique violation and returns
-- "Already clocked in" to the worker. The `clockOutWorker` action picks
-- the most-recent open log (ORDER BY clock_in DESC LIMIT 1) — that
-- behavior is unchanged.
-- ============================================================================

CREATE UNIQUE INDEX IF NOT EXISTS
  time_tracking_logs_one_open_per_worker_idx
  ON time_tracking_logs (worker_id)
  WHERE clock_out IS NULL;

COMMENT ON INDEX time_tracking_logs_one_open_per_worker_idx IS
  'Cycle 2: enforces at most one open clock-in per worker. Catches concurrent / retry race in field app.';
