'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'

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

  const newTag = convertFormData<CreateTagParams>(formData)
  await createTag(newTag)

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

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

  await deleteTag(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')

  await linkTagsToContact(tagId, contactIds)

  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')

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