import { NextRequest, NextResponse } from 'next/server';
import { readFile, readdir, stat } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
import { getSession } from '@/lib/auth';

const SOURCE_EXTS = ['.cbl', '.cob', '.cpy', '.pli', '.rpg', '.f', '.f90', '.py', '.java', '.cs'];

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 filePath = request.nextUrl.searchParams.get('path');
  const dirPath = request.nextUrl.searchParams.get('dir');

  if (dirPath) {
    if (!existsSync(dirPath)) {
      return NextResponse.json({ error: 'Directory not found' }, { status: 404 });
    }
    try {
      const entries = await readdir(dirPath);
      const files: string[] = [];
      for (const entry of entries) {
        const full = join(dirPath, entry);
        const s = await stat(full);
        if (s.isFile() && SOURCE_EXTS.some(ext => entry.toLowerCase().endsWith(ext))) {
          files.push(full);
        }
      }
      return NextResponse.json({ files });
    } catch {
      return NextResponse.json({ error: 'Failed to read directory' }, { status: 500 });
    }
  }

  if (!filePath) {
    return NextResponse.json({ error: 'path or dir is required' }, { status: 400 });
  }

  if (!existsSync(filePath)) {
    return NextResponse.json({ error: 'File not found' }, { status: 404 });
  }

  try {
    const content = await readFile(filePath, 'utf-8');
    return NextResponse.json({ content, path: filePath });
  } catch {
    return NextResponse.json({ error: 'Failed to read file' }, { status: 500 });
  }
}
