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, 'github')
    ),
  });

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

  const { searchParams } = new URL(request.url);
  const page = searchParams.get('page') ?? '1';
  const q = searchParams.get('q') ?? '';
  const org = searchParams.get('org') ?? ''; // empty = personal account

  const headers = {
    Authorization: `Bearer ${account.accessToken}`,
    Accept: 'application/vnd.github+json',
    'X-GitHub-Api-Version': '2022-11-28',
  };

  // Build API URL based on context
  let apiUrl: string;
  if (q) {
    // Search: scope to org or to the authenticated user
    const scope = org ? `org:${org}` : 'user:@me';
    apiUrl = `https://api.github.com/search/repositories?q=${encodeURIComponent(q)}+${scope}&sort=updated&per_page=50&page=${page}`;
  } else if (org) {
    apiUrl = `https://api.github.com/orgs/${encodeURIComponent(org)}/repos?sort=updated&per_page=50&page=${page}&type=all`;
  } else {
    apiUrl = `https://api.github.com/user/repos?sort=updated&per_page=50&page=${page}&affiliation=owner,collaborator`;
  }

  const res = await fetch(apiUrl, { headers });

  if (!res.ok) {
    return NextResponse.json({ connected: false, repos: [] });
  }

  const data = await res.json();
  const items = q ? data.items : data;

  const repos = (items as any[]).map((r: any) => ({
    id: r.id,
    name: r.name,
    fullName: r.full_name,
    description: r.description,
    private: r.private,
    language: r.language,
    updatedAt: r.updated_at,
    cloneUrl: r.clone_url,
    htmlUrl: r.html_url,
    defaultBranch: r.default_branch,
  }));

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