import { z } from "zod";
import prisma from "@/server/db/prisma";
import { parseJson } from "@/server/http/parse";
import { ok } from "@/server/http/response";
import { parseIdParam } from "@/server/http/schemas";
import { withErrorHandling } from "@/server/http/withErrorHandling";

const ContactCardUpdateSchema = z.object({
  name: z.string().min(1),
  phone: z.string().min(1),
  email: z.string().email(),
});

export const PUT = withErrorHandling(
  async (request: Request, { params }: { params: Promise<{ id: string }> }) => {
    const id = await parseIdParam(params);
    const data = await parseJson(request, ContactCardUpdateSchema);
    const card = await prisma.contactcard.update({
      where: { id },
      data: { name: data.name, phone: data.phone, email: data.email },
    });
    return ok(card);
  },
);

export const DELETE = withErrorHandling(
  async (request: Request, { params }: { params: Promise<{ id: string }> }) => {
    const id = await parseIdParam(params);
    await prisma.contactcard.delete({
      where: { id },
    });
    return ok({ success: true });
  },
);
