import { NextResponse } from "next/server";
import { getSessionCustomer, updateCustomerProfile } from "../../../lib/customerAuth";

export async function GET() {
  const session = await getSessionCustomer();
  if (!session) return NextResponse.json({ profile: null }, { status: 401 });
  return NextResponse.json({ profile: session.customer });
}

export async function PATCH(request: Request) {
  const session = await getSessionCustomer();
  if (!session) return NextResponse.json({ ok: false, reason: "Bitte zuerst einloggen." }, { status: 401 });

  const body = await request.json().catch(() => null);
  const { firstName, lastName, deliveryMethod, street, packstationNumber, postNumber, zip, city, country } = body ?? {};
  if (
    typeof firstName !== "string" ||
    !firstName ||
    typeof lastName !== "string" ||
    !lastName ||
    (deliveryMethod !== "address" && deliveryMethod !== "packstation") ||
    typeof zip !== "string" ||
    !zip ||
    typeof city !== "string" ||
    !city ||
    typeof country !== "string" ||
    !country
  ) {
    return NextResponse.json({ ok: false, reason: "Bitte alle Pflichtfelder ausfüllen." }, { status: 400 });
  }
  if (deliveryMethod === "address" && !street) {
    return NextResponse.json({ ok: false, reason: "Bitte Straße und Hausnummer angeben." }, { status: 400 });
  }
  if (deliveryMethod === "packstation" && (!packstationNumber || !postNumber)) {
    return NextResponse.json({ ok: false, reason: "Bitte Packstation- und Postnummer angeben." }, { status: 400 });
  }

  const result = await updateCustomerProfile(session.token, session.customer.id, {
    firstName,
    lastName,
    deliveryMethod,
    street,
    packstationNumber,
    postNumber,
    zip,
    city,
    country,
  });
  return NextResponse.json(result, { status: result.ok ? 200 : 400 });
}
