"use server"

import { revalidatePath } from "next/cache"

import prisma from "@/lib/prisma"
import {
  CreateRecipientFormType,
  createRecipientSchema,
  UpdateRecipientFormType,
  updateRecipientSchema,
} from "@/lib/schemas/recipients.schemas"
import { RecipientService } from "@/services/recipient.service"

export async function createNewRecipient(formData: CreateRecipientFormType) {
  const validatedFields = createRecipientSchema.safeParse(formData)

  if (!validatedFields.success) {
    return {
      success: false,
      errors: validatedFields.error.flatten().fieldErrors,
    }
  }

  const { username, firstName, lastName, department, email, phone } =
    validatedFields.data

  try {
    const existingRecipientUsername =
      await RecipientService.findByUsername(username)

    if (existingRecipientUsername) {
      return {
        success: false,
        errors: {
          username: ["Username already exists"],
        },
      }
    }

    const existingRecipientEmail = await RecipientService.findByEmail(
      email || "",
    )

    if (existingRecipientEmail) {
      return {
        success: false,
        errors: {
          email: ["Email already exists"],
        },
      }
    }

    await RecipientService.create({
      username: username || (firstName[0] + lastName).toLowerCase(),
      firstName,
      lastName,
      department: department,
      email: email || null,
      phone: phone || null,
    })

    revalidatePath("/recipients")

    return {
      success: true,
      message: "Recipient created successfully",
    }
  } catch (error) {
    console.error("Database error:", error)
    return {
      message: "Failed to create recipient",
    }
  }
}

export async function updateRecipient(formData: UpdateRecipientFormType) {
  const validatedFields = updateRecipientSchema.safeParse(formData)

  if (!validatedFields.success) {
    return {
      success: false,
      errors: validatedFields.error.flatten().fieldErrors,
    }
  }

  const { id, username, firstName, lastName, department, email, phone } =
    validatedFields.data

  try {
    const existingRecipient = await RecipientService.findByUsername(username)

    if (existingRecipient && existingRecipient.id !== id) {
      return {
        success: false,
        errors: {
          username: ["Username already exists"],
        },
      }
    }

    const existingRecipientEmail = await RecipientService.findByEmail(
      email || "",
    )

    if (existingRecipientEmail && existingRecipientEmail.id !== id) {
      return {
        success: false,
        errors: {
          email: ["Email already exists"],
        },
      }
    }

    await prisma.recipient.update({
      where: { id },
      data: {
        username,
        firstName,
        lastName,
        department: department,
        email: email || null,
        phone: phone || null,
      },
    })

    revalidatePath("/recipients")

    return {
      success: true,
      message: "Recipient updated successfully",
    }
  } catch (error) {
    console.error("Database error:", error)
    return {
      message: "Failed to update recipient",
    }
  }
}
