import { randomUUID } from 'node:crypto'
import { isValidGroupDisplayId, normalizeGroupDisplayId } from '@/lib/groups/groupDisplayId'
import type { getDb } from '@/server/db'

type AppDb = Awaited<ReturnType<typeof getDb>>

const UUID_V4_REGEX =
    /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i

export function newGroupId(): string {
    return randomUUID()
}

export function isUuidV4(value: string): boolean {
    return UUID_V4_REGEX.test(value)
}

/** 將網址參數解析為內部 group_id（支援 display_id 或 group_id） */
export async function resolveGroupIdFromParam(db: AppDb, param: string): Promise<string | null> {
    const key = String(param ?? '').trim()
    if (!key) return null
    const row = await db.get<{ group_id: string }>(
        `SELECT group_id FROM groups WHERE display_id = ? OR group_id = ? LIMIT 1`,
        [key, key]
    )
    return row?.group_id ?? null
}

export async function isGroupDisplayIdTaken(
    db: AppDb,
    displayId: string,
    excludeGroupId?: string
): Promise<boolean> {
    const id = normalizeGroupDisplayId(displayId)
    if (!id) return false
    const row = excludeGroupId
        ? await db.get<{ ok: number }>(
              `SELECT 1 AS ok FROM groups WHERE display_id = ? AND group_id != ? LIMIT 1`,
              [id, excludeGroupId]
          )
        : await db.get<{ ok: number }>(`SELECT 1 AS ok FROM groups WHERE display_id = ? LIMIT 1`, [id])
    return Boolean(row?.ok)
}

/** 從舊 group_id 推斷是否可作為 display_id */
export function legacyGroupIdAsDisplayId(value: string): string | null {
    const s = String(value ?? '').trim()
    if (isValidGroupDisplayId(s)) return s
    return null
}
