import { asyncHandler } from "@/core/asyncHandler"
import { paymentConfigService } from "./payment-config.service"
import { CreateShopPaymentMethodConfigSchema, CreateStationPaymentMethodConfigSchema, UpdateShopPaymentMethodConfigSchema, UpdateStationPaymentMethodConfigSchema } from "ttm-shared"
import { z } from "zod"
import { Request, Response } from "express"

const ConfigIdParamsSchema = z.object({
    configId: z.string().uuid()
})

export const getPaymentConfigMeta = asyncHandler(async (req: Request, res: Response) => {
    const meta = await paymentConfigService.getMeta(req.shop!.id, req.shop!.ownerId)
    res.json(meta)
})

export const getShopPaymentMethodConfigs = asyncHandler(async (req: Request, res: Response) => {
    const rows = await paymentConfigService.listShopConfigs(req.shop!.id)
    res.json(rows)
})

export const createShopPaymentMethodConfig = asyncHandler(async (req: Request, res: Response) => {
    const input = CreateShopPaymentMethodConfigSchema.parse(req.body)
    const created = await paymentConfigService.createShopConfig(req.shop!.id, req.shop!.ownerId, input)
    res.status(201).json(created)
})

export const updateShopPaymentMethodConfig = asyncHandler(async (req: Request, res: Response) => {
    const { configId } = ConfigIdParamsSchema.parse(req.params)
    const input = UpdateShopPaymentMethodConfigSchema.parse(req.body)
    const updated = await paymentConfigService.updateShopConfig(req.shop!.id, req.shop!.ownerId, configId, input)
    res.json(updated)
})

export const deleteShopPaymentMethodConfig = asyncHandler(async (req: Request, res: Response) => {
    const { configId } = ConfigIdParamsSchema.parse(req.params)
    await paymentConfigService.deleteShopConfig(req.shop!.id, configId)
    res.status(204).send()
})

export const getStationPaymentMethodConfigs = asyncHandler(async (req: Request, res: Response) => {
    const rows = await paymentConfigService.listStationConfigsForShop(req.shop!.id)
    res.json(rows)
})

export const createStationPaymentMethodConfig = asyncHandler(async (req: Request, res: Response) => {
    const input = CreateStationPaymentMethodConfigSchema.parse(req.body)
    const created = await paymentConfigService.createStationConfig(req.shop!.id, req.shop!.ownerId, input)
    res.status(201).json(created)
})

export const updateStationPaymentMethodConfig = asyncHandler(async (req: Request, res: Response) => {
    const { configId } = ConfigIdParamsSchema.parse(req.params)
    const input = UpdateStationPaymentMethodConfigSchema.parse(req.body)
    const updated = await paymentConfigService.updateStationConfig(req.shop!.id, req.shop!.ownerId, configId, input)
    res.json(updated)
})

export const deleteStationPaymentMethodConfig = asyncHandler(async (req: Request, res: Response) => {
    const { configId } = ConfigIdParamsSchema.parse(req.params)
    await paymentConfigService.deleteStationConfig(req.shop!.id, configId)
    res.status(204).send()
})

