BEGIN;

DO $$
DECLARE
  t text;
  seq_name text;
  max_id bigint;
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: public.<table>_id_seq
    seq_name := format('public.%I_id_seq', t);

    -- Drop IDENTITY only if the column is identity (safe to re-run)
    IF EXISTS (
      SELECT 1
      FROM information_schema.columns
      WHERE table_schema = 'public'
        AND table_name   = t
        AND column_name  = 'id'
        AND is_identity  = 'YES'
    ) THEN
      EXECUTE format('ALTER TABLE public.%I ALTER COLUMN id DROP IDENTITY', t);
    END IF;

    -- Ensure sequence exists
    EXECUTE format('CREATE SEQUENCE IF NOT EXISTS %s', seq_name);

    -- Set default like bigserial
    EXECUTE format(
      'ALTER TABLE public.%I ALTER COLUMN id SET DEFAULT nextval(''%s'')',
      t, seq_name
    );

    -- Own the sequence by the column
    EXECUTE format(
      'ALTER SEQUENCE %s OWNED BY public.%I.id',
      seq_name, t
    );

    -- Sync sequence to MAX(id) + 1 to avoid duplicate key
    EXECUTE format('SELECT COALESCE(MAX(id), 0) FROM public.%I', t) INTO max_id;

    EXECUTE format('SELECT setval(''%s'', $1, false)', seq_name)
      USING (max_id + 1);
  END LOOP;
END $$;

COMMIT;
