'use server'
import {revalidatePath} from 'next/cache'
import {convertFormData} from '@/lib/convertFormData'
import type {CreateTagParams} from '@/dal/tags'
import {disconnectTagsFromContact} from '@/dal/tags'
import {linkTagsToContact} from '@/dal/tags'
import {createTag, deleteTag} from '@/dal/tags'
import {getLogger} from '@/lib/logger'
import {getSessionProfileFromCookie} from '@/lib/sessionUtils'

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

  const newTag = convertFormData<CreateTagParams>(formData)

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

  await createTag({...newTag, userId: profile.id})

  revalidatePath('/tags')
  logger.info('createTagAction completed successfully')
}

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

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

  await deleteTag(id, profile.id)

  revalidatePath('/tags')
  logger.info('deleteTagAction completed successfully')
}

/**
 * Link one or more tags to a contact.
 *
 * @param tagId The id of the tag to link.
 * @param contactIds The ids of the contacts to link to the tag.
 */
export async function linkTagsToContactsServerFunction({
  tagId,
  contactIds,
}: {
  tagId: string
  contactIds: string[]
}): Promise<void> {
  const logger = await getLogger()
  logger.info('linkTagsToContactsAction called')

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

  await linkTagsToContact(tagId, contactIds, profile.id)

  revalidatePath(`/tags/${tagId}`)
  logger.info('linkTagsToContactsAction completed successfully')
}

/**
 * Remove one or more tags from a contact.
 *
 * @param tagId The id of the tag to link.
 * @param contactIds The ids of the contacts to remove from the tag.
 */
export async function unlinkTagsFromContactServerFunction({
  tagId,
  contactIds,
}: {
  tagId: string
  contactIds: string[]
}): Promise<void> {
  const logger = await getLogger()
  logger.info('unlinkTagsToContactsAction called')

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

  await disconnectTagsFromContact(tagId, contactIds, profile.id)

  revalidatePath(`/tags/${tagId}`)
  logger.info('unlinkTagsToContactsAction completed successfully')
}
