import { NextRequest } from "next/server";
import { z } from "zod";
import { getSession } from "../../../../lib/auth/session";
import { getPrisma } from "../../../../lib/db";
import { ok, fail } from "../../../../lib/http";
import { sanitizeText } from "../../../../lib/auth/validation";

export const runtime = "nodejs";

const Body = z.object({
  firstName: z.string().min(1),
  lastName: z.string().min(1),
  gender: z.string().optional().nullable(),
  dob: z.string().optional().nullable(),
  address: z.string().optional().nullable(),
  avatarUrl: z.string().optional().nullable(),
  email: z.string().optional(), // included in profile but not updatable
});

export async function GET() {
  const session = await getSession();
  if (!session) return fail(new Error("Unauthorized"), { status: 401 });

  const prisma = await getPrisma();
  if (!prisma) return fail(new Error("Database not configured"), { status: 503 });

  const user = await prisma.user.findUnique({ where: { id: session.sub } });
  if (!user) return fail(new Error("Invalid user"));

  return ok({
    profile: {
      firstName: user.firstName,
      lastName: user.lastName,
      gender: user.gender,
      dob: user.dob ? user.dob.toISOString().slice(0, 10) : "",
      address: user.address,
      avatarUrl: user.image,
      email: user.email,
    },
  });
}

export async function POST(req: NextRequest) {
  const session = await getSession();
  if (!session) return fail(new Error("Unauthorized"), { status: 401 });

  const prisma = await getPrisma();
  if (!prisma) return fail(new Error("Database not configured"), { status: 503 });

  const body = await req.json().catch(() => ({}));
  const parsed = Body.safeParse(body);
  if (!parsed.success) {
    console.error("Validation error:", parsed.error.errors);
    return fail(new Error("Invalid input: " + parsed.error.errors.map(e => e.message).join(", ")));
  }

  const data = parsed.data;
  await prisma.user.update({
    where: { id: session.sub },
    data: {
      firstName: sanitizeText(data.firstName),
      lastName: sanitizeText(data.lastName),
      gender: data.gender ? sanitizeText(data.gender) : null,
      dob: data.dob ? new Date(data.dob) : null,
      address: data.address ? sanitizeText(data.address) : null,
      image: data.avatarUrl ? data.avatarUrl : null,
    },
  });

  return ok({ message: "Profile updated" });
}
