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

// Maps Bitbucket language names → our sourceLanguages IDs
const BITBUCKET_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': 'bash',
  'JCL': 'jcl',
  'TSQL': 'db2',
  'SQLPL': 'db2',
  'PLpgSQL': 'oracle',
};

function getAuthHeader(token: string): string {
  return token.includes(':')
    ? `Basic ${Buffer.from(token).toString('base64')}`
    : `Bearer ${token}`;
}

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

  if (!account?.accessToken) return NextResponse.json({ detected: null, breakdown: [] });

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

  const res = await fetch(
    `https://api.bitbucket.org/2.0/repositories/${encodeURIComponent(workspace)}/${encodeURIComponent(repo)}`,
    {
      headers: {
        Authorization: getAuthHeader(account.accessToken),
        Accept: 'application/json',
      },
    }
  );

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

  const data = await res.json();
  
  // Bitbucket doesn't provide language breakdown directly in the repo endpoint
  // We need to fetch it from a different endpoint or estimate from file extensions
  // For now, we'll use the language field if available, or return empty
  const language = data.language;
  
  if (!language) {
    // Fallback: try to get languages from the commits endpoint or files
    // This is a simplified approach - in production you'd want to scan files
    return NextResponse.json({ detected: null, breakdown: [] });
  }

  // Bitbucket returns a single language string, not a breakdown
  // We'll create a breakdown with 100% for the detected language
  const breakdown = [{
    name: language,
    scribaId: BITBUCKET_TO_SCRIBA[language] ?? null,
    percent: 100,
  }];

  const detected = breakdown.find(b => b.scribaId !== null) ?? null;

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