'use server'

import {
	CategoriesOnProducts,
	CategoryLocale,
	Lang,
	Product,
	ProductLocale,
	ProductResource,
	ProductToStore
} from '@prisma/client'

import {STORE_ID} from '@/lib/config/constants'
import {db, dbQueryLog} from '@/lib/db/prisma/client'

export interface ProductProps extends Product {
	locales: ProductLocale[]
	toStore: ProductToStore[]
	categoriesOnProducts: CategoriesOnProducts[]
	resources: ProductResource[]
}

export const getProductBySlug = async (data: {
	slug: string
	lang: string
}): Promise<ProductLocale | null> => {
	return db.productLocale.findFirst({
		where: {
			slug: data.slug,
			lang: data.lang as Lang
		}
	})
}

export const getProductById = async (id: unknown): Promise<Product | null> => {
	return db.product.findUnique({
		where: {id: id as number},
		include: {
			resources: true,
			categoriesOnProducts: {
				where: {
					storeId: STORE_ID
				},
				include: {
					category: {
						include: {
							locales: {
								orderBy: {
									lang: 'asc'
								}
							}
						}
					}
				}
			},
			locales: {
				orderBy: {
					lang: 'asc'
				},
				include: {
					meta: true
				}
			},
			toStore: true
		}
	})
}

export const getProducts = async (): Promise<Product[] | null> => {
	return db.product.findMany({
		include: {
			locales: {
				orderBy: {
					lang: 'asc'
				},
				omit: {
					description: true,
					content: true,
					instruction: true
				},
				include: {
					meta: true
				}
			},
			toStore: true
		}
	})
}

export const getProductResources = async (
	productId: number | null
): Promise<ProductResource[] | null> => {
	return db.productResource.findMany({
		where: {
			productId: productId
		}
	})
}
