'use server'

import {CategoryLocale} from '@prisma/client'
import {z} from 'zod'

import {getCategoryBySlug} from '@/actions/model/category'
import {i18nLocalesCodes} from '@/i18n-config'
import {STORE_ID} from '@/lib/config/constants'
import {db} from '@/lib/db/prisma/client'
import {createCategoryFormSchema} from '@/lib/schemas/admin/category'
import {cleanEmptyParams, dbErrorHandling, slug as slugger} from '@/lib/utils'

export const onCategoryCreateAction = async (
	formData: z.infer<typeof createCategoryFormSchema>
) => {
	const validatedData = createCategoryFormSchema.parse(formData)

	if (!validatedData) {
		return {error: 'Недійсні вхідні дані'}
	}

	if (validatedData.locales.length < i18nLocalesCodes.length) {
		return {error: 'Заповніть всі мови'}
	}

	const locales: CategoryLocale[] = []

	for (const i in validatedData.locales) {
		const locale = validatedData.locales[i]

		const {title, lang} = locale
		const slug = slugger(title, lang)
		const result = await getCategoryBySlug({slug, lang})

		if (!result) {
			const normalized: any = cleanEmptyParams({slug, ...locale})
			locales.push(normalized)
		} else {
			return {error: `Категорія ${title} вже існує`}
		}
	}

	try {
		const newCategory = await db.category.create({
			data: {
				storeId: STORE_ID,
				status: true,
				// position: 0,
				locales: {
					create: locales
				}
			}
		})

		return {success: JSON.stringify(newCategory, null, 2)}
	} catch (error) {
		return dbErrorHandling(error)
	}
}
