import { Request, Response, NextFunction } from "express"
import { prisma } from "../core/prisma"
import { AppError } from "../core/AppError"

function firstParam(value: unknown): string | undefined {
    if (typeof value === "string") return value
    if (Array.isArray(value) && typeof value[0] === "string") return value[0]
    return undefined
}

export const attachShop = async (
    req: Request,
    _res: Response,
    next: NextFunction
) => {

    if (!req.auth) {
        throw new AppError("Unauthorized", 401)
    }

    let shopId: string | undefined

    if (req.auth.type === "admin") {
        // Priorité URL scoppée, fallback header pour routes legacy/non-scoppées
        shopId = firstParam(req.params.shopId)
        if (!shopId) {
            const headerShop = req.headers["x-shop-id"]
            shopId = firstParam(headerShop)
        }

        if (!shopId) {
            throw new AppError("Shop id missing", 400)
        }
    }

    if (req.auth.type === "pos") {
        // JWT est shop-agnostic → lire le shopId depuis le header X-Shop-Id
        shopId = firstParam(req.headers["x-shop-id"])

        if (!shopId) {
            throw new AppError("Shop id missing (X-Shop-Id header required)", 400)
        }

        // Vérifier que ce POS user appartient bien à ce shop
        const membership = await prisma.shopUser.findFirst({
            where: { id: req.auth.sub, shopId, active: true },
            select: { id: true }
        })
        if (!membership) {
            throw new AppError("Forbidden: not a member of this shop", 403)
        }
    }

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

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

    if (req.auth.type === "admin" && shop.ownerId !== req.auth.sub) {
        throw new AppError("Forbidden", 403)
    }

    req.shop = shop

    next()
}