import { Request, Response } from "express"
import { asyncHandler } from "@/core/asyncHandler"
import {
    PosLoginSchema,
    PosSelectShopSchema,
    PosSwitchShopSchema,
    RefreshSchema,
    FirstLoginPasswordChangeSchema,
    type PosLoginResponse,
    type ShopUserLoginResponse,
    type PosProfileResponse,
    type SwitchShopResponse
} from "ttm-shared"

import { posAuthService } from "./pos-auth.service"

export const login = asyncHandler(async (req: Request, res: Response) => {
    const { email, password } = PosLoginSchema.parse(req.body)

    const result: PosLoginResponse = await posAuthService.login(email, password)

    res.json(result)
})

export const selectShop = asyncHandler(async (req: Request, res: Response) => {
    const { sessionToken, shopId } = PosSelectShopSchema.parse(req.body)

    const result: ShopUserLoginResponse = await posAuthService.selectShop(sessionToken, shopId)

    res.json(result)
})

export const refresh = asyncHandler(async (req: Request, res: Response) => {
    const { refreshToken } = RefreshSchema.parse(req.body)

    const result = await posAuthService.refresh(refreshToken)

    res.json(result)
})

export const changePassword = asyncHandler(async (req: Request, res: Response) => {
    if (!req.auth || req.auth.type !== "pos") {
        return res.status(403).json({ message: "Forbidden" })
    }

    const { newPassword } = FirstLoginPasswordChangeSchema.parse(req.body)

    const result = await posAuthService.changePassword(req.auth.sub, newPassword)

    res.json(result)
})

/**
 * GET /auth/pos/me — profil complet du ShopUser connecté + shops disponibles
 */
export const getProfile = asyncHandler(async (req: Request, res: Response) => {
    if (!req.auth || req.auth.type !== "pos") {
        return res.status(403).json({ message: "Forbidden" })
    }

    const result: PosProfileResponse = await posAuthService.getProfile(req.auth.sub)

    res.json(result)
})

/**
 * POST /auth/pos/switch-shop — changer de shop sans re-login
 */
export const switchShop = asyncHandler(async (req: Request, res: Response) => {
    if (!req.auth || req.auth.type !== "pos") {
        return res.status(403).json({ message: "Forbidden" })
    }

    const { shopId } = PosSwitchShopSchema.parse(req.body)

    const result: SwitchShopResponse = await posAuthService.switchShop(req.auth.sub, shopId)

    res.json(result)
})

