import { Request, Response } from "express"
import { asyncHandler } from "@/core/asyncHandler"
import { shopService } from "./shop.service"
import { shopEventService } from "./shop-event.service"
import { UpdateShopSchema } from "ttm-shared"
import { z } from "zod"

const createShopSchema = z.object({
    name: z.string().min(2)
})

const ParamsSchema = z.object({
    id: z.uuid()
})

const ShopIdParamSchema = z.object({
    shopId: z.uuid()
})

const GetEventsQuerySchema = z.object({
    since: z.string().optional(),
    limit: z.coerce.number().int().positive().max(1000).default(100)
})

export const getShopEvents = asyncHandler(
    async (req: Request, res: Response) => {
        const { id: shopId } = ParamsSchema.parse(req.params)
        const { since, limit } = GetEventsQuerySchema.parse(req.query)

        const sinceBigInt = since ? BigInt(since) : 0n

        const result = await shopEventService.queryEventsSince(shopId, sinceBigInt, limit)

        if (result.status === 410) {
            return res.status(410).json(result)
        }

        res.json(result)
    }
)

export const createShop = asyncHandler(
    async (req: Request, res: Response) => {

        // Ici protect + requireAdmin garantissent auth
        const ownerId = req.auth!.sub

        const { name } = createShopSchema.parse(req.body)

        const shop = await shopService.create(name, ownerId, req.senderSocketId)

        res.status(201).json(shop)
    }
)

export const updateShop = asyncHandler(
    async (req: Request, res: Response) => {

        if (!req.auth || req.auth.type !== "admin") {
            throw new Error("Unauthorized")
        }

        const { shopId } = ShopIdParamSchema.parse(req.params)

        const input = UpdateShopSchema.parse(req.body)

        const shop = await shopService.update(
            shopId,
            input,
            req.auth.sub,
            req.senderSocketId
        )

        res.json(shop)
    }
)

export const deleteShop = asyncHandler(
    async (req: Request, res: Response) => {

        if (!req.auth || req.auth.type !== "admin") {
            throw new Error("Unauthorized")
        }

        const { id } = ParamsSchema.parse(req.params)

        await shopService.remove(
            id,
            req.auth.sub,
            req.senderSocketId
        )

        res.json({ success: true })
    }
)

export const getMyShops = asyncHandler(
    async (req: Request, res: Response) => {
        const ownerId = req.auth!.sub
        const shops = await shopService.findAllForUser(ownerId)

        res.json(shops)
    }
)

export const getShopById = asyncHandler(
    async (req: Request, res: Response) => {
        const { id: shopId } = ParamsSchema.parse(req.params)
        const ownerId = req.auth!.sub

        const shop = await shopService.findById(shopId)

        // Vérifier que l'admin est propriétaire du shop
        if (shop.ownerId !== ownerId) {
            throw new Error("Unauthorized - not owner of this shop")
        }

        res.json(shop)
    }
)


