import { query } from '../db/client.js' type AdminUserRow = { id: number username: string display_name: string password_hash: string role: string status: string phone: string phone_bound_at: string | null phone_bound_by: number | null test_account: boolean session_version: number created_at: string updated_at: string device_id?: string | null device_bound_at?: string | null device_last_used_at?: string | null } type AdminUserCreateInput = { username: string displayName: string passwordHash: string role: string status: string phone?: string phoneBoundAt?: string | null phoneBoundBy?: number | null testAccount?: boolean createdAt: string updatedAt: string } type AdminUserPatch = Partial< Pick< AdminUserRow, | 'username' | 'display_name' | 'password_hash' | 'role' | 'status' | 'phone' | 'phone_bound_at' | 'phone_bound_by' | 'test_account' | 'session_version' | 'updated_at' > > type AdminUserListInput = { page?: number pageSize?: number keyword?: string role?: string status?: string } type AdminUserListResult = { items: AdminUserRow[] total: number } const ADMIN_USER_SELECT = ` SELECT au.*, d.device_id AS device_id, d.bound_at AS device_bound_at, d.last_used_at AS device_last_used_at FROM admin_users au LEFT JOIN admin_user_devices d ON d.user_id = au.id AND d.status = 'active' ` export async function getAdminUserById(userId: number | string): Promise { const result = await query(`${ADMIN_USER_SELECT} WHERE au.id = $1 LIMIT 1`, [ Number(userId), ]) return result.rows[0] || null } export async function getAdminUserByUsername(username: string): Promise { const result = await query(`${ADMIN_USER_SELECT} WHERE au.username = $1 LIMIT 1`, [ String(username || '') .trim() .toLowerCase(), ]) return result.rows[0] || null } export async function getAdminUserByPhone(phone: string): Promise { const result = await query(`${ADMIN_USER_SELECT} WHERE au.phone = $1 LIMIT 1`, [ String(phone || '').trim(), ]) return result.rows[0] || null } export async function createAdminUser(input: AdminUserCreateInput): Promise { const result = await query<{ [column: string]: unknown; id: number }>( ` INSERT INTO admin_users ( username, display_name, password_hash, role, status, phone, phone_bound_at, phone_bound_by, test_account, session_version, created_at, updated_at ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) RETURNING id `, [ input.username, input.displayName, input.passwordHash, input.role, input.status, String(input.phone || '').trim(), input.phoneBoundAt || null, input.phoneBoundBy ?? null, input.testAccount === true, 1, input.createdAt, input.updatedAt, ], ) return getAdminUserById(result.rows[0]?.id || 0) } export async function updateAdminUser( userId: number | string, patch: AdminUserPatch, ): Promise { const current = await getAdminUserById(userId) if (!current) { return null } const next = { ...current, ...patch } const result = await query<{ [column: string]: unknown; id: number }>( ` UPDATE admin_users SET username = $1, display_name = $2, password_hash = $3, role = $4, status = $5, phone = $6, phone_bound_at = $7, phone_bound_by = $8, test_account = $9, session_version = $10, updated_at = $11 WHERE id = $12 RETURNING id `, [ next.username, next.display_name, next.password_hash, next.role, next.status, String(next.phone || '').trim(), next.phone_bound_at || null, next.phone_bound_by ?? null, next.test_account === true, Number(next.session_version || 1), next.updated_at, Number(userId), ], ) return getAdminUserById(result.rows[0]?.id || 0) } export async function listAdminUsers({ page = 1, pageSize = 20, keyword = '', role = '', status = '', }: AdminUserListInput = {}): Promise { const offset = (page - 1) * pageSize const filters: string[] = [] const params: unknown[] = [] if (keyword) { params.push(`%${keyword}%`) filters.push( `(au.username ILIKE $${params.length} OR au.display_name ILIKE $${params.length} OR au.phone ILIKE $${params.length})`, ) } if (role) { params.push(role) filters.push(`au.role = $${params.length}`) } if (status) { params.push(status) filters.push(`au.status = $${params.length}`) } const whereClause = filters.length > 0 ? `WHERE ${filters.join(' AND ')}` : '' const totalResult = await query<{ [column: string]: unknown; total: number }>( `SELECT COUNT(*)::int AS total FROM admin_users au ${whereClause}`, params, ) params.push(pageSize) params.push(offset) const itemsResult = await query( ` ${ADMIN_USER_SELECT} ${whereClause} ORDER BY au.id DESC LIMIT $${params.length - 1} OFFSET $${params.length} `, params, ) return { items: itemsResult.rows, total: Number(totalResult.rows[0]?.total || 0), } } export async function countActiveAdminUsers(): Promise { const result = await query<{ [column: string]: unknown; total: number }>( `SELECT COUNT(*)::int AS total FROM admin_users WHERE role = 'admin' AND status = 'active'`, ) return Number(result.rows[0]?.total || 0) }