import { apiError, requireOwner } from "@/lib/auth";
import { ensureSchema, rawDb } from "@/lib/db";
import { oauthConfig, type Platform } from "@/lib/meta";

export async function GET(request: Request) {
  try {
    const ownerId = requireOwner(request);
    const url = new URL(request.url);
    const platform = url.searchParams.get("platform") as Platform;
    const brandId = url.searchParams.get("brandId");
    if ((platform !== "instagram" && platform !== "threads") || !brandId) throw new Error("잘못된 연결 요청입니다.");
    const config = oauthConfig(platform, request.url);
    if (!config.appId || !config.appSecret) {
      const destination = new URL("/", request.url);
      destination.searchParams.set("view", "brands");
      destination.searchParams.set("oauth", "missing-config");
      destination.searchParams.set("platform", platform);
      return Response.redirect(destination, 302);
    }
    await ensureSchema();
    const db = rawDb();
    const brand = await db.prepare("SELECT id FROM brands WHERE id = ? AND owner_id = ?").bind(brandId, ownerId).first();
    if (!brand) throw new Error("브랜드를 찾을 수 없습니다.");
    const state = crypto.randomUUID();
    const now = Date.now();
    await db.prepare("DELETE FROM oauth_states WHERE expires_at < ?").bind(now).run();
    await db.prepare("INSERT INTO oauth_states (id, owner_id, brand_id, platform, expires_at, created_at) VALUES (?, ?, ?, ?, ?, ?)")
      .bind(state, ownerId, brandId, platform, now + 10 * 60 * 1000, now).run();
    const authorize = new URL(config.authorizeUrl);
    authorize.searchParams.set("client_id", config.appId);
    authorize.searchParams.set("redirect_uri", config.redirectUri);
    authorize.searchParams.set("response_type", "code");
    authorize.searchParams.set("scope", config.scope);
    authorize.searchParams.set("state", state);
    if (platform === "instagram") {
      authorize.searchParams.set("enable_fb_login", "0");
      authorize.searchParams.set("force_authentication", "1");
    }
    return Response.redirect(authorize, 302);
  } catch (error) { return apiError(error); }
}
