-- Migration: add fail_count and locked to clauth_machines
-- Run via: clauth install (picks this up automatically) or apply manually

ALTER TABLE clauth_machines
  ADD COLUMN IF NOT EXISTS fail_count  INTEGER NOT NULL DEFAULT 0,
  ADD COLUMN IF NOT EXISTS locked      BOOLEAN NOT NULL DEFAULT false;

-- Index for fast lockout checks
CREATE INDEX IF NOT EXISTS idx_clauth_machines_locked
  ON clauth_machines (machine_hash, locked);

-- Admin helper: unlock a machine
-- Usage: SELECT clauth_unlock_machine('your_machine_hash');
CREATE OR REPLACE FUNCTION clauth_unlock_machine(p_machine_hash TEXT)
RETURNS void
LANGUAGE plpgsql
SECURITY DEFINER
AS $$
BEGIN
  UPDATE clauth_machines
  SET locked = false, fail_count = 0
  WHERE machine_hash = p_machine_hash;
END;
$$;

REVOKE EXECUTE ON FUNCTION clauth_unlock_machine(TEXT) FROM PUBLIC;
