import { notFound, redirect } from "next/navigation";
import { db } from "@/lib/db";
import {
  centsToDollars,
  parseBool,
  parseDollarsToCents,
  parseInt10,
  parseStringTrim,
  parseTags,
  tagsToInputValue,
} from "@/lib/forms";
import { ServiceForm, type ServiceFormValues } from "../_form";

export const metadata = { title: "Edit service — TouchBase" };
export const dynamic = "force-dynamic";

type Params = Promise<{ id: string }>;

async function updateService(formData: FormData): Promise<void> {
  "use server";
  const id = parseStringTrim(formData.get("id"));
  const name = parseStringTrim(formData.get("name"));
  if (!id || !name) return;
  await db.service.update({
    where: { id },
    data: {
      name,
      description: parseStringTrim(formData.get("description")) || null,
      durationMin: parseInt10(formData.get("durationMin"), 60),
      bufferAfterMin: parseInt10(formData.get("bufferAfterMin"), 15),
      priceCents: parseDollarsToCents(formData.get("priceDollars")),
      depositCents: parseDollarsToCents(formData.get("depositDollars")),
      requiredTherapistTags: parseTags(formData.get("requiredTherapistTags")),
      requiredRoomTags: parseTags(formData.get("requiredRoomTags")),
      active: parseBool(formData.get("active")),
    },
  });
  redirect("/admin/services");
}

export default async function EditServicePage({
  params,
}: {
  params: Params;
}) {
  const { id } = await params;
  const service = await db.service.findUnique({ where: { id } });
  if (!service) notFound();

  const values: ServiceFormValues = {
    name: service.name,
    description: service.description ?? "",
    durationMin: service.durationMin,
    bufferAfterMin: service.bufferAfterMin,
    priceDollars: centsToDollars(service.priceCents),
    depositDollars: centsToDollars(service.depositCents),
    requiredTherapistTags: tagsToInputValue(service.requiredTherapistTags),
    requiredRoomTags: tagsToInputValue(service.requiredRoomTags),
    active: service.active,
  };

  return (
    <ServiceForm
      action={updateService}
      values={values}
      submitLabel="Save changes"
      id={id}
    />
  );
}
