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({ branches: [] });

  const { searchParams } = new URL(request.url);
  const org = searchParams.get('org');
  const project = searchParams.get('project');
  const repoId = searchParams.get('repoId');
  if (!org || !project || !repoId) return NextResponse.json({ branches: [] });

  const basicAuth = Buffer.from(`:${account.accessToken}`).toString('base64');
  const res = await fetch(
    `https://dev.azure.com/${encodeURIComponent(org)}/${encodeURIComponent(project)}/_apis/git/repositories/${repoId}/refs?filter=heads/&api-version=7.0&$top=100`,
    { headers: { Authorization: `Basic ${basicAuth}` } }
  );

  if (!res.ok) return NextResponse.json({ branches: [] });
  const data = await res.json();
  const branches = (data.value ?? []).map((b: any) => b.name.replace('refs/heads/', ''));
  return NextResponse.json({ branches });
}
