import { randomUUID } from 'node:crypto' import { DEFAULT_USER_PASSWORD } from '~~/shared/auth' import { randomToken } from './base64url' import { hashPassword } from './password' import { getSqlClient } from './postgres' let databaseReadyPromise: Promise | null = null export async function ensureDatabaseReady() { if (!databaseReadyPromise) { databaseReadyPromise = initializeDatabase() } return databaseReadyPromise } async function initializeDatabase() { const sql = getSqlClient() await sql` create table if not exists users ( id text primary key, username text not null unique, full_name text not null, phone_number text, role text not null check (role in ('super_admin', 'staff')), password_hash text not null, must_change_password boolean not null default true, is_active boolean not null default true, created_by text references users(id) on delete set null, created_at timestamptz not null default now(), updated_at timestamptz not null default now(), last_login_at timestamptz ) ` await sql` alter table users add column if not exists phone_number text ` await sql` create table if not exists user_passkeys ( id text primary key, user_id text not null references users(id) on delete cascade, credential_id text not null unique, public_key text not null, counter bigint not null default 0, device_type text not null check (device_type in ('singleDevice', 'multiDevice')), backed_up boolean not null default false, transports jsonb not null default '[]'::jsonb, label text not null, created_at timestamptz not null default now(), last_used_at timestamptz ) ` await sql` create index if not exists user_passkeys_user_id_idx on user_passkeys (user_id) ` await sql` create table if not exists bookings ( id text primary key, confirmation_token text not null unique, receipt_token text not null unique, customer_name text not null, customer_phone text not null, booking_mode text not null check (booking_mode in ('table', 'seat')), quantity integer not null check (quantity >= 1), seat_count integer not null check (seat_count >= 1), ticket_type text not null check (ticket_type in ('vip', 'supporter')), unit_price integer not null check (unit_price >= 0), total_price integer not null check (total_price >= 0), person_in_charge_id text not null references users(id) on delete restrict, person_in_charge_name text not null, person_in_charge_phone_number text not null, status text not null check (status in ('pending', 'confirmed')) default 'pending', confirmed_at timestamptz, created_at timestamptz not null default now(), updated_at timestamptz not null default now() ) ` await sql` alter table bookings add column if not exists receipt_token text ` await sql` create unique index if not exists bookings_receipt_token_idx on bookings (receipt_token) ` await sql` create table if not exists booking_seats ( id text primary key, booking_id text not null references bookings(id) on delete cascade, seat_number integer not null check (seat_number >= 1), seat_token text not null unique, recipient_name text, recipient_phone text, shared_at timestamptz, created_at timestamptz not null default now(), updated_at timestamptz not null default now(), unique (booking_id, seat_number) ) ` await sql` create index if not exists booking_seats_booking_id_idx on booking_seats (booking_id) ` await sql` create table if not exists booking_settings ( id text primary key, total_tables integer, total_seats integer, updated_at timestamptz not null default now() ) ` await sql` alter table booking_settings add column if not exists total_seats integer ` await sql` insert into booking_settings (id) values ('default') on conflict (id) do nothing ` const bookingsMissingReceiptTokens = await sql<{ id: string }[]>` select id from bookings where receipt_token is null or receipt_token = '' ` for (const booking of bookingsMissingReceiptTokens) { await sql` update bookings set receipt_token = ${randomToken(24)}, updated_at = now() where id = ${booking.id} ` } await sql` alter table bookings drop constraint if exists bookings_booking_mode_check ` await sql` alter table bookings add constraint bookings_booking_mode_check check (booking_mode in ('table', 'pax', 'seat')) ` await sql` update bookings set booking_mode = 'seat', updated_at = now() where booking_mode = 'pax' ` await sql` alter table bookings drop constraint if exists bookings_booking_mode_check ` await sql` alter table bookings add constraint bookings_booking_mode_check check (booking_mode in ('table', 'seat')) ` await sql` update booking_settings set total_seats = total_tables * 10, updated_at = now() where total_seats is null and total_tables is not null ` const existingBookings = await sql<{ id: string, seat_count: number | string }[]>` select id, seat_count from bookings ` for (const booking of existingBookings) { const seatCount = typeof booking.seat_count === 'number' ? booking.seat_count : Number.parseInt(booking.seat_count, 10) const existingSeatRows = await sql<{ seat_number: number | string }[]>` select seat_number from booking_seats where booking_id = ${booking.id} ` const existingSeatNumbers = new Set( existingSeatRows.map((seat) => typeof seat.seat_number === 'number' ? seat.seat_number : Number.parseInt(seat.seat_number, 10)) ) for (let seatNumber = 1; seatNumber <= seatCount; seatNumber += 1) { if (existingSeatNumbers.has(seatNumber)) { continue } await sql` insert into booking_seats ( id, booking_id, seat_number, seat_token ) values ( ${randomUUID()}, ${booking.id}, ${seatNumber}, ${randomToken(24)} ) on conflict (booking_id, seat_number) do nothing ` } } await sql` alter table bookings alter column receipt_token set not null ` const [existingSuperAdmin] = await sql<{ id: string }[]>` select id from users where username = 'xiaomai' limit 1 ` if (!existingSuperAdmin) { const passwordHash = await hashPassword(DEFAULT_USER_PASSWORD) await sql` insert into users ( id, username, full_name, role, password_hash, must_change_password, is_active, created_by ) values ( ${randomUUID()}, 'xiaomai', 'Xiaomai', 'super_admin', ${passwordHash}, true, true, null ) ` } await sql` update users set phone_number = '601157753558', updated_at = now() where username = 'xiaomai' and (phone_number is null or phone_number = '') ` }