'use server'
import {Prisma} from '@prisma/client'
import DAL from '@dal'
import {revalidatePath} from 'next/cache'
import {getSessionProfileAndOptionallyRenew} from '@mediators'

/**
 * Create a new tag
 */
export async function createTag(newTag: Prisma.TagCreateInput): Promise<void> {
  const profile = await getSessionProfileAndOptionallyRenew()
  await DAL.createTag(profile.id, newTag)
  revalidatePath('/tags')
}

/**
 * Delete a tag.
 */
export async function deleteTag(id: string): Promise<void> {
  const profile = await getSessionProfileAndOptionallyRenew()
  await DAL.deleteTag(profile.id, id)
  revalidatePath('/tags')
}

/**
 * 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 linkTagsToContacts({tagId, contactIds}: {tagId: string; contactIds: string[]}): Promise<void> {
  const profile = await getSessionProfileAndOptionallyRenew()
  await DAL.linkTagToContact(profile.id, tagId, contactIds)
  revalidatePath(`/tags/${tagId}`)
}

/**
 * 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 unlinkTagsFromContact({tagId, contactId}: {tagId: string; contactId: string[]}): Promise<void> {
  const profile = await getSessionProfileAndOptionallyRenew()
  await DAL.disconnectTagFromContact(profile.id, tagId, contactId)
  revalidatePath(`/tags/${tagId}`)
}
