import { NextResponse } from "next/server"; import { cookies } from "next/headers"; import type { PatientProfile, PatientProfileUpdate } from "@duoc-thu/shared-types"; import { SESSION_COOKIE } from "../auth/session"; const GATEWAY_URL = process.env.API_GATEWAY_URL ?? "http://localhost:3000"; export async function GET() { const token = cookies().get(SESSION_COOKIE)?.value; if (!token) { return NextResponse.json({ error: "not_authenticated" }, { status: 401 }); } let upstream: Response; try { upstream = await fetch(`${GATEWAY_URL}/auth/patient-profile`, { headers: { Authorization: `Bearer ${token}` }, cache: "no-store", }); } catch { return NextResponse.json({ error: "gateway_unreachable" }, { status: 502 }); } if (!upstream.ok) { return NextResponse.json({ error: "not_authenticated" }, { status: 401 }); } const profile = (await upstream.json()) as PatientProfile; return NextResponse.json(profile); } export async function PUT(request: Request) { const token = cookies().get(SESSION_COOKIE)?.value; if (!token) { return NextResponse.json({ error: "not_authenticated" }, { status: 401 }); } let body: PatientProfileUpdate; try { body = (await request.json()) as PatientProfileUpdate; } catch { return NextResponse.json({ error: "invalid_body" }, { status: 400 }); } let upstream: Response; try { upstream = await fetch(`${GATEWAY_URL}/auth/patient-profile`, { method: "PUT", headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, body: JSON.stringify(body), cache: "no-store", }); } catch { return NextResponse.json({ error: "gateway_unreachable" }, { status: 502 }); } if (!upstream.ok) { return NextResponse.json( { error: "save_failed" }, { status: upstream.status === 401 ? 401 : 502 } ); } const profile = (await upstream.json()) as PatientProfile; return NextResponse.json(profile); }