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

// GET: Fetch all active social links
export const GET = withErrorHandling(async () => {
  const socialLinks = await prisma.sociallink.findMany({
    where: { isActive: true },
    orderBy: { order: "asc" },
  });
  return ok(socialLinks);
});

// POST: Add a new social link
const SocialLinkCreateSchema = z.object({
  platform: z.string().min(1),
  url: z.string().min(1),
  icon: z.string().min(1),
  order: z.number().int().optional(),
});

export const POST = withErrorHandling(async (request: Request) => {
  const body = await parseJson(request, SocialLinkCreateSchema);
  const newSocialLink = await prisma.sociallink.create({
    data: {
      platform: body.platform,
      url: body.url,
      icon: body.icon,
      order: body.order ?? 0,
      isActive: true,
    },
  });
  return ok(newSocialLink);
});

// PUT: Update a social link
const SocialLinkUpdateSchema = z.object({
  id: z.number().int(),
  platform: z.string().min(1).optional(),
  url: z.string().min(1).optional(),
  icon: z.string().min(1).optional(),
  order: z.number().int().optional(),
  isActive: z.boolean().optional(),
});

export const PUT = withErrorHandling(async (request: Request) => {
  const body = await parseJson(request, SocialLinkUpdateSchema);
  const { id, ...data } = body;
  const updatedSocialLink = await prisma.sociallink.update({
    where: { id },
    data,
  });
  return ok(updatedSocialLink);
});

// DELETE: Delete a social link
export const DELETE = withErrorHandling(async (request: Request) => {
  const { id } = await parseJson(request, DeleteByIdSchema);
  await prisma.sociallink.delete({ where: { id } });
  return ok({ message: "Social link deleted successfully" });
});
