BEGIN;

DO $$
DECLARE
  t text;
  seq_name text;
BEGIN
  FOREACH t IN ARRAY ARRAY[
    'daily_checklist_activity_task_assignments',
    'daily_checklist_activity_tasks',
    'daily_checklist_phases',
    'daily_checklist_tasks',
    'daily_checklists',
    'employee_kandangs',
    'employees',
    'phase_activities',
    'phases'
  ]
  LOOP
    -- Sequence name convention
    seq_name := format('public.%I_id_seq', t);

    -- 1) Drop default nextval (bigserial behavior)
    EXECUTE format(
      'ALTER TABLE public.%I ALTER COLUMN id DROP DEFAULT',
      t
    );

    -- 2) Add IDENTITY back (BY DEFAULT is safer for rollback)
    EXECUTE format(
      'ALTER TABLE public.%I ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY',
      t
    );

    -- 3) Detach & optionally drop sequence (safe)
    IF EXISTS (
      SELECT 1 FROM pg_class
      WHERE relkind = 'S'
        AND relname = t || '_id_seq'
    ) THEN
      EXECUTE format(
        'ALTER SEQUENCE %s OWNED BY NONE',
        seq_name
      );

      -- Optional: drop sequence (comment if you want to keep it)
      EXECUTE format(
        'DROP SEQUENCE IF EXISTS %s',
        seq_name
      );
    END IF;

  END LOOP;
END $$;

COMMIT;
