-- Auto-assign employee_number on user insert if not provided
CREATE OR REPLACE FUNCTION assign_employee_number()
RETURNS TRIGGER AS $$
DECLARE next_num INT;
BEGIN
  IF NEW.employee_number IS NULL OR NEW.employee_number = '' THEN
    SELECT COALESCE(MAX(employee_number::int), 1000) + 1
    INTO next_num
    FROM "user"
    WHERE employee_number ~ '^\d+$';
    NEW.employee_number := next_num::text;
  END IF;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS trg_assign_employee_number ON "user";
CREATE TRIGGER trg_assign_employee_number
  BEFORE INSERT ON "user"
  FOR EACH ROW
  EXECUTE FUNCTION assign_employee_number();

-- Backfill any users missing an employee number
DO $$ DECLARE r RECORD; num INT;
BEGIN
  SELECT COALESCE(MAX(employee_number::int), 1000) INTO num FROM "user" WHERE employee_number ~ '^\d+$';
  FOR r IN (SELECT id FROM "user" WHERE employee_number IS NULL OR employee_number = '' ORDER BY created_at) LOOP
    num := num + 1;
    UPDATE "user" SET employee_number = num::text WHERE id = r.id;
  END LOOP;
END $$;
