import { NextResponse } from "next/server";
import { createOAuthState, isSettingEnabled, siteUrl, STATE_COOKIE_PREFIX } from "@/lib/auth";

export async function GET(request: Request) {
  const publicUrl = siteUrl(request);
  if (!(await isSettingEnabled("auth_enabled")) || !(await isSettingEnabled("auth_yandex_enabled"))) return NextResponse.redirect(new URL("/?auth=disabled", publicUrl));
  const clientId = process.env.YANDEX_CLIENT_ID;
  const redirectUri = process.env.YANDEX_REDIRECT_URI || `${publicUrl}/api/auth/yandex/callback`;
  if (!clientId) return NextResponse.redirect(new URL("/?auth=not-configured", publicUrl));
  const state = createOAuthState();
  const url = new URL("https://oauth.yandex.ru/authorize");
  url.search = new URLSearchParams({ response_type: "code", client_id: clientId, redirect_uri: redirectUri, state, scope: "login:default_phone login:info login:avatar", force_confirm: "yes" }).toString();
  const response = NextResponse.redirect(url);
  response.cookies.set(`${STATE_COOKIE_PREFIX}yandex`, state, { httpOnly: true, sameSite: "lax", secure: process.env.NODE_ENV === "production", maxAge: 600, path: "/" });
  return response;
}
