import { NextRequest, NextResponse } from 'next/server';
import { getSession } from '@/lib/auth';
import { db, schema } from '@/lib/db';
import { eq, and } from 'drizzle-orm';

export async function GET(request: NextRequest) {
  const session = await getSession(request.cookies.get('scriba.access_token')?.value);
  if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const account = await db.query.accounts.findFirst({
    where: and(eq(schema.accounts.userId, session.user.id), eq(schema.accounts.providerId, 'azure')),
  });

  if (!account?.accessToken) return NextResponse.json({ connected: false, orgs: [] });

  const basicAuth = Buffer.from(`:${account.accessToken}`).toString('base64');

  // Get profile to retrieve user ID
  const profileRes = await fetch(
    'https://app.vssps.visualstudio.com/_apis/profile/profiles/me?api-version=6.0',
    { headers: { Authorization: `Basic ${basicAuth}` } }
  );
  if (!profileRes.ok) return NextResponse.json({ connected: false, orgs: [] });
  const profile = await profileRes.json();

  // Get organizations for this user
  const orgsRes = await fetch(
    `https://app.vssps.visualstudio.com/_apis/accounts?memberId=${profile.id}&api-version=6.0`,
    { headers: { Authorization: `Basic ${basicAuth}` } }
  );
  if (!orgsRes.ok) return NextResponse.json({ connected: true, orgs: [] });

  const data = await orgsRes.json();
  const orgs = (data.value ?? []).map((o: any) => ({
    login: o.accountName,
    url: o.accountUri,
  }));

  return NextResponse.json({ connected: true, orgs });
}
