import { Request, Response } from "express"
import { asyncHandler } from "../../core/asyncHandler"
import { shopUserService } from "./shop-user.service"
import { CreateShopUserSchema, UpdateShopUserSchema } from "ttm-shared"
import { z } from "zod"

const UserIdParamSchema = z.object({
    userId: z.string().uuid()
})

/**
 * GET /me/shop-users — tous les ShopUsers des shops de l'admin connecté
 */
export const getMyShopUsers = asyncHandler(
    async (req: Request, res: Response) => {
        if (!req.auth || req.auth.type !== "admin") {
            throw new Error("Unauthorized")
        }

        const users = await shopUserService.findAllByOwner(req.auth.sub)
        res.json(users)
    }
)

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

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

        const shopId = req.shop!.id
        const input = CreateShopUserSchema.parse(req.body)

        const shopUser = await shopUserService.create(
            shopId,
            input,
            req.auth.sub,
            req.senderSocketId
        )

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

export const getShopUsers = asyncHandler(
    async (req: Request, res: Response) => {
        if (!req.auth || req.auth.type !== "admin") {
            throw new Error("Unauthorized")
        }

        const shopId = req.shop!.id
        const users = await shopUserService.findAllByShop(shopId, req.auth.sub)

        res.json(users)
    }
)

export const updateShopUser = asyncHandler(
    async (req: Request, res: Response) => {
        if (!req.auth || req.auth.type !== "admin") {
            throw new Error("Unauthorized")
        }

        const { userId } = UserIdParamSchema.parse(req.params)
        const shopId = req.shop!.id
        const input = UpdateShopUserSchema.parse(req.body)

        const user = await shopUserService.update(shopId, userId, input, req.auth.sub, req.senderSocketId)

        res.json(user)
    }
)

export const deleteShopUser = asyncHandler(
    async (req: Request, res: Response) => {
        if (!req.auth || req.auth.type !== "admin") {
            throw new Error("Unauthorized")
        }

        const { userId } = UserIdParamSchema.parse(req.params)
        const shopId = req.shop!.id

        await shopUserService.delete(shopId, userId, req.auth.sub, req.senderSocketId)

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