import { GROUP_DISPLAY_ID_AUTO_START } from '@/lib/groups/groupDisplayId'
import type { getDb } from '@/server/db'
import { isGroupDisplayIdTaken } from '@/server/groups/groupIdUtils'

type AppDb = Awaited<ReturnType<typeof getDb>>

const MAX_ATTEMPTS = 64

/**
 * 分配下一個家族 display_id：數字遞增，且不小於 GROUP_DISPLAY_ID_AUTO_START（20000000）。
 */
export async function allocateNextGroupDisplayId(db: AppDb): Promise<string> {
    const row = await db.get<{ maxId: number | null }>(
        `SELECT MAX(CAST(display_id AS INTEGER)) AS maxId
         FROM groups
         WHERE display_id GLOB '[0-9]*'`
    )
    const maxExisting = Number(row?.maxId ?? 0)
    let candidate = Math.max(maxExisting, GROUP_DISPLAY_ID_AUTO_START - 1) + 1

    for (let i = 0; i < MAX_ATTEMPTS; i++) {
        const id = String(candidate)
        if (!(await isGroupDisplayIdTaken(db, id))) {
            return id
        }
        candidate += 1
    }

    throw new Error('Failed to allocate group display_id')
}
