"use server"

import { revalidatePath } from "next/cache"

import {
  CreateCategoryFormType,
  createCategorySchema,
  UpdateCategoryFormType,
  updateCategorySchema,
} from "@/lib/schemas/category.schemas"
import { CategoryService } from "@/services/category.service"

export async function createCategoryAction(formData: CreateCategoryFormType) {
  const validatedFields = createCategorySchema.safeParse(formData)

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

  try {
    const existingCategory = await CategoryService.findByName(
      validatedFields.data.name,
    )

    if (existingCategory) {
      return {
        success: false,
        errors: {
          name: ["Category already exists"],
        },
      }
    }

    await CategoryService.create(validatedFields.data)

    revalidatePath("/inventory/categories")

    return {
      success: true,
      message: "Category created successfully",
    }
  } catch (error) {
    console.error("Database error:", error)
    return {
      success: false,
      message: "Failed to create category",
      errors: {
        name: ["Category already exists"],
      },
    }
  }
}

export async function updateCategoryAction(formData: UpdateCategoryFormType) {
  const validatedFields = updateCategorySchema.safeParse(formData)

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

  const { id, name } = validatedFields.data

  try {
    const existingCategory = await CategoryService.findById(id)

    if (!existingCategory) {
      return {
        success: false,
        errors: { id: ["Category not found"] },
      }
    }

    if (existingCategory.name === name) {
      return {
        success: false,
        errors: { name: ["Category name is the same as the old one"] },
      }
    }

    if (await CategoryService.findByName(name)) {
      return {
        success: false,
        errors: { name: ["Category already exists"] },
      }
    }

    await CategoryService.update(id, {
      name,
    })

    revalidatePath("/inventory/categories")

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

export async function deleteCategoryAction(formData: FormData) {
  const { id } = Object.fromEntries(formData) as { id: string }

  try {
    const existingCategory = await CategoryService.findAllWithItemsCount()
    const category = existingCategory.find((category) => category.id === id)

    if (!category) {
      return {
        success: false,
        errors: {
          id: ["Category not found"],
        },
      }
    }

    if (category._count.items && category._count.items > 0) {
      return {
        success: false,
        errors: {
          id: ["Category has items"],
        },
      }
    }

    await CategoryService.delete(id)

    revalidatePath("/inventory/categories")

    return {
      success: true,
      message: "Category deleted successfully",
    }
  } catch (error) {
    console.error("Database error:", error)
    return {
      success: false,
      message: "Failed to delete category",
    }
  }
}
