// app/api/auth/set-session/route.ts
// In Next.js App Router, use createRouteHandlerClient to ensure auth cookies are attached to responses.
export const runtime = "nodejs";

import { NextResponse, NextRequest } from "next/server";
import { cookies } from "next/headers";
import { createServerClient } from "@supabase/ssr";

/**
 * Pose la session Supabase côté serveur (cookies httpOnly) à partir de l'access_token et du refresh_token fournis.
 * Nettoie aussi les cookies d'orga staff et le cache me_cache_v1 pour repartir propre.
 */
export async function POST(req: NextRequest) {
  try {
    const { access_token, refresh_token } = await req.json();

    if (!access_token || !refresh_token) {
      return NextResponse.json({ error: "missing_tokens" }, { status: 400 });
    }

    const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
    const anon = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;
    if (!supabaseUrl || !anon) {
      return NextResponse.json({ error: "misconfigured_supabase" }, { status: 500 });
    }
    const res = NextResponse.json({ ok: true });
    const supabase = createServerClient(supabaseUrl, anon, {
      cookies: {
        get(name) {
          return req.cookies.get(name)?.value;
        },
        set(name, value, options) {
          res.cookies.set({ name, value, ...options });
        },
        remove(name, options) {
          res.cookies.set({ name, value: "", ...options, maxAge: 0 });
        },
      },
    });

    // Pose la session serveur
    const { error } = await supabase.auth.setSession({ access_token, refresh_token });
    if (error) {
      return NextResponse.json({ error: "set_session_failed", message: error.message }, { status: 400 });
    }

    // Cleanup potentially stale context cookies
    res.cookies.set({ name: "active_org_id", value: "", path: "/", maxAge: 0 });
    res.cookies.set({ name: "active_org_id", value: "", path: "/staff", maxAge: 0 });
    res.cookies.set({ name: "me_cache_v1", value: "", path: "/", maxAge: 0 });

    return res;
  } catch (e: any) {
    return NextResponse.json({ error: "server_error", message: e?.message || "unknown" }, { status: 500 });
  }
}