'use server'

import {revalidatePath} from 'next/cache'
import {redirect} from 'next/navigation'
import {convertFormData} from '@/lib/convertFormData'
import type {CreateMeetingParams, UpdateMeetingParams} from '@/dal/meetings'
import {createMeeting, deleteMeeting, updateMeeting} from '@/dal/meetings'
import {getLogger} from '@/lib/logger'
import {getSessionProfileFromCookie} from '@/lib/sessionUtils'

export async function createMeetingAction(_prevData: unknown, formData: FormData): Promise<void> {
  const logger = await getLogger()
  logger.info('createMeetingAction called')

  const meeting = convertFormData<CreateMeetingParams>(formData)

  const profile = await getSessionProfileFromCookie()
  if (!profile) {
    logger.warn(`Unauthenticated user tried calling createMeetingActions`)
    return
  }

  await createMeeting({...meeting, userId: profile.id})

  revalidatePath('/meetings')
  logger.info('createMeetingAction completed successfully')
}

export async function updateMeetingAction(_prevData: unknown, formData: FormData): Promise<void> {
  const logger = await getLogger()
  logger.info('updateMeetingAction called')

  const meeting = convertFormData<UpdateMeetingParams>(formData)

  const profile = await getSessionProfileFromCookie()
  if (!profile) {
    logger.warn(`Unauthenticated user tried calling updateMeetingAction`)
    return
  }

  await updateMeeting({...meeting, userId: profile.id})

  logger.info('updateMeetingAction completed successfully')
  redirect(`/meetings`)
}

export async function cancelMeetingServerFunction({id}: {id: string}): Promise<void> {
  const logger = await getLogger()
  logger.info('cancelMeetingAction called')

  const profile = await getSessionProfileFromCookie()
  if (!profile) {
    logger.warn(`Unauthenticated user tried calling cancelMeetingAction`)
    return
  }

  await deleteMeeting(id, profile.id)

  logger.info('cancelMeetingAction completed successfully')
  redirect('/meetings')
}
