import { NextResponse } from "next/server";
import { cookies } from "next/headers";
import { createSession, getOrCreateUser, isSettingEnabled, SESSION_COOKIE, siteUrl, STATE_COOKIE_PREFIX } from "@/lib/auth";
import { attachVerifiedPhone } from "@/lib/sms-pin";

export async function GET(request: Request) {
  const url = new URL(request.url);
  const publicUrl = siteUrl(request);
  if (!(await isSettingEnabled("auth_enabled")) || !(await isSettingEnabled("auth_yandex_enabled"))) return NextResponse.redirect(new URL("/?auth=disabled", publicUrl));
  if (!url.searchParams.get("state") || url.searchParams.get("state") !== (await cookies()).get(`${STATE_COOKIE_PREFIX}yandex`)?.value) return NextResponse.redirect(new URL("/?auth=error", publicUrl));
  try {
    const redirectUri = process.env.YANDEX_REDIRECT_URI || `${publicUrl}/api/auth/yandex/callback`;
    const tokenResponse = await fetch("https://oauth.yandex.ru/token", { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded", authorization: `Basic ${Buffer.from(`${process.env.YANDEX_CLIENT_ID}:${process.env.YANDEX_CLIENT_SECRET}`).toString("base64")}` }, body: new URLSearchParams({ grant_type: "authorization_code", code: url.searchParams.get("code") || "", redirect_uri: redirectUri }), cache: "no-store" });
    const token = await tokenResponse.json() as { access_token?: string; scope?: string };
    if (!token.access_token) throw new Error("Yandex token exchange failed");
    const profile = await fetch("https://login.yandex.ru/info?format=json", { headers: { authorization: `OAuth ${token.access_token}` }, cache: "no-store" }).then((r) => r.json()) as { id?: string; display_name?: string; real_name?: string; default_email?: string; default_avatar_id?: string; default_phone?: { number?: string } };
    if (!profile.id) throw new Error("Yandex profile is empty");
    const user = await getOrCreateUser("yandex", profile.id, { email: profile.default_email, displayName: profile.real_name || profile.display_name || "Пользователь", avatarUrl: profile.default_avatar_id ? `https://avatars.yandex.net/get-yapic/${profile.default_avatar_id}/islands-200` : undefined });
    const phoneAttached = profile.default_phone?.number ? await attachVerifiedPhone(user.id, profile.default_phone.number) : false;
    console.info("Yandex OAuth profile received", {
      userId: user.id,
      grantedScopes: token.scope || null,
      hasDefaultPhone: Boolean(profile.default_phone?.number),
      phoneAttached
    });
    const session = await createSession(user.id);
    const response = NextResponse.redirect(new URL("/?auth=success", publicUrl));
    response.cookies.set(SESSION_COOKIE, session, { httpOnly: true, sameSite: "lax", secure: process.env.NODE_ENV === "production", maxAge: 30 * 24 * 60 * 60, path: "/" });
    response.cookies.delete(`${STATE_COOKIE_PREFIX}yandex`);
    return response;
  } catch { return NextResponse.redirect(new URL("/?auth=error", publicUrl)); }
}
