import { NextRequest, NextResponse } from 'next/server';
import fs from 'fs/promises';
import path from 'path';
import { loadPlanoImage } from '@/lib/image-service';

const PROJECTS_DIR = path.join(process.cwd(), 'projects');

async function findCapDir(capitulosDir: string, numero: string) {
  const dirs = await fs.readdir(capitulosDir, { withFileTypes: true });
  return dirs.find(d =>
    d.isDirectory() && d.name.startsWith(numero.padStart(2, '0'))
  );
}

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ slug: string; numero: string; planoId: string }> }
) {
  try {
    const { slug, numero, planoId } = await params;
    const capitulosDir = path.join(PROJECTS_DIR, slug, 'capitulos');
    const capDir = await findCapDir(capitulosDir, numero);

    if (!capDir) {
      return NextResponse.json({ error: 'Capítulo no encontrado' }, { status: 404 });
    }

    const imageBuffer = await loadPlanoImage(slug, capDir.name, planoId);

    if (!imageBuffer) {
      return NextResponse.json({ error: 'Imagen no encontrada' }, { status: 404 });
    }

    return new NextResponse(new Uint8Array(imageBuffer), {
      headers: {
        'Content-Type': 'image/png',
        'Cache-Control': 'no-cache',
      },
    });
  } catch (error: any) {
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
