import { cookies } from "next/headers";
import { NextResponse } from "next/server";

import { gatewayFetch } from "@/lib/api/gateway";
import { REFRESH_TOKEN_COOKIE } from "@/lib/auth/constants";
import { clearAuthCookies, setAuthCookies } from "@/lib/auth/cookies";

export const dynamic = "force-dynamic";

export async function POST() {
  const refreshToken = (await cookies()).get(REFRESH_TOKEN_COOKIE)?.value;
  if (!refreshToken) {
    return NextResponse.json({ error: "Not authenticated." }, { status: 401 });
  }

  const res = await gatewayFetch("/v1/auth/refresh", {
    method: "POST",
    body: JSON.stringify({ refresh_token: refreshToken }),
  });
  const data = await res.json().catch(() => null);

  if (!res.ok || !data?.access_token) {
    // Refresh token invalid/expired/rotated — force re-login.
    return clearAuthCookies(
      NextResponse.json({ error: "Session expired." }, { status: 401 })
    );
  }

  const out = NextResponse.json({ ok: true, user: data.user });
  return setAuthCookies(
    out,
    data.access_token,
    data.refresh_token,
    data.expires_in ?? 900
  );
}
