'use server'
import {revalidatePath} from 'next/cache'
import {createTag, deleteTag, disconnectTagsFromContact, linkTagsToContact} from '@/dal/tags'
import {protectedFormAction, protectedServerFunction} from '@/lib/serverFunctions'
import {createTagSchema, deleteTagSchema, linkUnlinkTagsToContactsSchema} from '@/schemas/tagSchemas'

export const createTagAction = protectedFormAction({
  schema: createTagSchema,
  serverFn: async ({data, profile}) => {
    await createTag({...data, userId: profile.id})
    revalidatePath('/tags')
  },
  functionName: 'Create tag action',
})

export const deleteTagServerFunction = protectedServerFunction({
  schema: deleteTagSchema,
  serverFn: async ({data, profile}) => {
    await deleteTag(data.id, profile.id)
    revalidatePath('/tags')
  },
  functionName: 'Delete tag action',
})

/**
 * 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 const linkTagsToContactsServerFunction = protectedServerFunction({
  schema: linkUnlinkTagsToContactsSchema,
  serverFn: async ({data, profile}) => {
    await linkTagsToContact(data.tagId, data.contactIds, profile.id)
    revalidatePath(`/tags/${data.tagId}`)
  },
  functionName: 'Link tags to contacts action',
})

/**
 * 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 const unlinkTagsFromContactServerFunction = protectedServerFunction({
  schema: linkUnlinkTagsToContactsSchema,
  serverFn: async ({data, profile}) => {
    await disconnectTagsFromContact(data.tagId, data.contactIds, profile.id)
    revalidatePath(`/tags/${data.tagId}`)
  },
  functionName: 'Unlink tags from contacts action',
})
