import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getDb } from "@/lib/db";
import { getProfile, updateProfile, type ProfileLink } from "@/lib/models";

export async function GET() {
  const profile = getProfile(getDb(), "de");
  // Beim GET liefern wir die DE-Sicht plus die Bio-Texte in beiden Sprachen,
  // damit das Formular beide Felder direkt anzeigen kann.
  return NextResponse.json({
    handle: profile.handle,
    realName: profile.realName,
    role: profile.role,
    location: profile.location,
    bioDe: getProfile(getDb(), "de").bio,
    bioEn: getProfile(getDb(), "en").bio,
    factsDe: getProfile(getDb(), "de").facts,
    factsEn: getProfile(getDb(), "en").facts,
    links: profile.links,
    updatedAt: profile.updatedAt,
  });
}

type ProfilePayload = {
  handle?: string;
  realName?: string;
  role?: string;
  location?: string;
  bioDe?: string;
  bioEn?: string;
  factsDe?: string[];
  factsEn?: string[];
  links?: ProfileLink[];
};

export async function PUT(req: NextRequest) {
  let body: ProfilePayload;
  try {
    body = (await req.json()) as ProfilePayload;
  } catch {
    return NextResponse.json({ error: "bad_request" }, { status: 400 });
  }
  if (body.handle !== undefined && (typeof body.handle !== "string" || body.handle.length === 0 || body.handle.length > 40)) {
    return NextResponse.json({ error: "invalid_handle" }, { status: 400 });
  }
  if (body.links !== undefined && !Array.isArray(body.links)) {
    return NextResponse.json({ error: "invalid_links" }, { status: 400 });
  }
  updateProfile(getDb(), {
    handle: body.handle,
    realName: body.realName,
    role: body.role,
    location: body.location,
    bioDe: body.bioDe,
    bioEn: body.bioEn,
    factsDe: body.factsDe,
    factsEn: body.factsEn,
    links: body.links,
  });
  return NextResponse.json({ ok: true });
}
