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

// Maps GitHub language names → our sourceLanguages IDs
const GITHUB_TO_SCRIBA: Record<string, string> = {
  'COBOL': 'cobol',
  'PL/I': 'pli',
  'PL/SQL': 'oracle',
  'PLSQL': 'oracle',
  'RPG': 'rpg',
  'Natural': 'natural',
  'Fortran': 'fortran',
  'Pascal': 'pascal',
  'Ada': 'ada',
  'Assembly': 'assembly',
  'Clipper': 'clipper',
  'FoxPro': 'clipper',
  'ABAP': 'sap',
  'Visual Basic 6.0': 'vb6',
  'Visual Basic': 'vb6',
  'ColdFusion': 'coldfusion',
  'PowerBuilder': 'powerbuilder',
  'SAS': 'sas',
  'Java': 'java',
  'C#': 'csharp',
  'Python': 'python',
  'JavaScript': 'javascript',
  'TypeScript': 'typescript',
  'PHP': 'php',
  'Ruby': 'ruby',
  'Go': 'go',
  'Rust': 'rust',
  'Swift': 'swift',
  'Kotlin': 'kotlin',
  'Scala': 'scala',
  'C': 'c',
  'C++': 'cpp',
  'Elixir': 'elixir',
  'Haskell': 'haskell',
  'Lua': 'lua',
  'Perl': 'perl',
  'Shell': 'shell',
  'JCL': 'jcl',
  'TSQL': 'db2',
  'SQLPL': 'db2',
  'PLpgSQL': 'oracle',
};

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({ detected: null, breakdown: [] });

  const { searchParams } = new URL(request.url);
  const owner = searchParams.get('owner');
  const repo = searchParams.get('repo');
  if (!owner || !repo) return NextResponse.json({ detected: null, breakdown: [] });

  const res = await fetch(
    `https://api.github.com/repos/${owner}/${repo}/languages`,
    {
      headers: {
        Authorization: `Bearer ${account.accessToken}`,
        Accept: 'application/vnd.github+json',
        'X-GitHub-Api-Version': '2022-11-28',
      },
    }
  );

  if (!res.ok) return NextResponse.json({ detected: null, breakdown: [] });

  const data = await res.json() as Record<string, number>;
  const total = Object.values(data).reduce((a, b) => a + b, 0);

  const breakdown = Object.entries(data)
    .sort(([, a], [, b]) => b - a)
    .map(([lang, bytes]) => ({
      name: lang,
      scribaId: GITHUB_TO_SCRIBA[lang] ?? null,
      bytes,
      percent: Math.round((bytes / total) * 100),
    }));

  // Best match: first language that maps to a known Scriba ID
  const detected = breakdown.find(b => b.scribaId !== null) ?? null;

  return NextResponse.json({ detected, breakdown, totalBytes: total });
}
