File size: 1,312 Bytes
9853b20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { insertRoom, updateCodesRoomId, getCodeById, updateCode } from './persistence'
import type { Database } from 'types/database'

export async function createRoom(codeId: string, linkedCodeId: string): Promise<string> {
  const room = await insertRoom({ status: 1, date_created: new Date().toISOString() })
  if (!room || !room.id) throw new Error('Failed to create room')

  const updated = await updateCodesRoomId([codeId, linkedCodeId], room.id)
  if (!updated || updated.length === 0) throw new Error('Failed to link codes to room')

  return room.id
}

export async function markCodeAsUsed(codeId: string, userId?: string, sessionHash?: string) {
  const existing = await getCodeById(codeId)
  if (!existing) throw new Error('Code not found when marking as used')

  const used_count = (existing.used_count || 0) + 1
  const date_first = existing.date_first || new Date().toISOString()

  const updateData: Database['public']['Tables']['codes']['Update'] = {
    used: 1,
    date_last: new Date().toISOString(),
    used_count,
    date_first
  }

  if (userId) updateData.user_id = userId
  if (sessionHash) updateData.session_hash = sessionHash

  const updated = await updateCode(codeId, updateData)
  if (!updated) throw new Error('Failed to mark code as used')
}