import { prisma } from "../../core/prisma";
import { AppError } from "../../core/AppError";
import { ShopDetailDto, UpdateShopInput } from "ttm-shared";
import { emitAdminEvent } from "../../core/adminEvents";


export const shopService = {
    async create(name: string, ownerId: string, senderSocketId?: string) {
        const shop = await prisma.shop.create({
            data: {
                name,
                ownerId
            }
        });

        emitAdminEvent(ownerId, {
            type: "shop.created",
            entity: "Shop",
            entityId: shop.id,
            payload: { id: shop.id, name: shop.name, ownerId, createdAt: shop.createdAt.toISOString() },
            createdAt: new Date().toISOString()
        }, senderSocketId)

        return shop;
    },

    async update(
        shopId: string,
        input: UpdateShopInput,
        ownerId: string,
        senderSocketId?: string
    ): Promise<ShopDetailDto> {

        const shop = await prisma.shop.update({
            where: { id: shopId, ownerId },
            data: {
                name: input.name,
                revision: { increment: 1 }
            }
        })

        if (!shop) {
            throw new AppError("Forbidden or not found", 403)
        }

        const result: ShopDetailDto = {
            id: shop.id,
            name: shop.name,
            createdAt: shop.createdAt.toISOString()
        }

        emitAdminEvent(ownerId, {
            type: "shop.updated",
            entity: "Shop",
            entityId: shop.id,
            payload: { id: shop.id, name: shop.name, revision: shop.revision },
            createdAt: new Date().toISOString()
        }, senderSocketId)

        return result
    },

    async findAllForUser(userId: string) {
        return prisma.shop.findMany({
            where: {
                ownerId: userId
            }
        })
    },

    async findById(shopId: string) {
        const shop = await prisma.shop.findUnique({
            where: { id: shopId }
        })

        if (!shop) {
            throw new AppError("Shop not found", 404)
        }

        return {
            id: shop.id,
            name: shop.name,
            ownerId: shop.ownerId,
            createdAt: shop.createdAt.toISOString()
        }
    },

    async remove(shopId: string, ownerId: string, senderSocketId?: string) {
        await prisma.shop.delete({
            where: { id: shopId }
        })
        emitAdminEvent(ownerId, {
            type: "shop.deleted",
            entity: "Shop",
            entityId: shopId,
            payload: { id: shopId },
            createdAt: new Date().toISOString()
        }, senderSocketId)
        return { success: true }
    }
}
