import { NextResponse, type NextRequest } from 'next/server';
import type { EmailOtpType } from '@supabase/supabase-js';
import { createClient } from '@/lib/supabase/server';

// E-postadaki bağlantı buraya gelir:
//   /auth/confirm?token_hash=...&type=magiclink   (giriş)
//   /auth/confirm?token_hash=...&type=invite      (öğrenci daveti)
//   /auth/confirm?code=...                         (PKCE akışı)
export async function GET(request: NextRequest) {
  const url = new URL(request.url);
  const tokenHash = url.searchParams.get('token_hash');
  const type = url.searchParams.get('type') as EmailOtpType | null;
  const code = url.searchParams.get('code');
  const supabase = await createClient();

  let ok = false;
  if (tokenHash && type) {
    const { error } = await supabase.auth.verifyOtp({ token_hash: tokenHash, type });
    ok = !error;
  } else if (code) {
    const { error } = await supabase.auth.exchangeCodeForSession(code);
    ok = !error;
  }

  const to = new URL(ok ? '/' : '/giris?hata=baglanti', url.origin);
  return NextResponse.redirect(to);
}
