import { Request, Response } from "express";
import { z } from "zod";
import { asyncHandler } from "../../core/asyncHandler";
import { AppError } from "../../core/AppError";
import { ingredientService } from "./ingredient.service";

const paramsSchema = z.object({
    id: z.string().uuid(),
});

const createSchema = z.object({
    name: z.string().min(1),
    allergen: z.boolean().optional().default(false),
    extraPrice: z.number().int().min(0).optional().default(0),
    imageUrl: z.string().optional().nullable(),
});

const updateSchema = createSchema.partial().extend({
    active: z.boolean().optional(),
});

export const getIngredients = asyncHandler(
    async (req: Request, res: Response) => {
        const ingredients = await ingredientService.findAll(req.shop!.id);
        res.json(ingredients);
    }
);

export const getAllIngredients = asyncHandler(
    async (req: Request, res: Response) => {
        const ingredients = await ingredientService.findAllIncludingInactive(req.shop!.id);
        res.json(ingredients);
    }
);

export const createIngredient = asyncHandler(
    async (req: Request, res: Response) => {
        const data = createSchema.parse(req.body);
        const ingredient = await ingredientService.create(
            req.shop!.id,
            data,
            req.auth?.sub,
            req.senderSocketId
        );
        res.status(201).json(ingredient);
    }
);

export const updateIngredient = asyncHandler(
    async (req: Request, res: Response) => {
        const { id } = paramsSchema.parse(req.params);
        const data = updateSchema.parse(req.body);

        const existing = await ingredientService.findById(req.shop!.id, id);
        if (!existing) {
            throw new AppError("Ingredient not found", 404);
        }

        const updated = await ingredientService.update(
            req.shop!.id,
            id,
            data,
            req.auth?.sub,
            req.senderSocketId
        );

        res.json(updated);
    }
);

export const deleteIngredient = asyncHandler(
    async (req: Request, res: Response) => {
        const { id } = paramsSchema.parse(req.params);

        const existing = await ingredientService.findById(req.shop!.id, id);
        if (!existing) {
            throw new AppError("Ingredient not found", 404);
        }

        await ingredientService.softDelete(
            req.shop!.id,
            id,
            req.auth?.sub,
            req.senderSocketId
        );

        res.status(204).send();
    }
);

