import { NextRequest, NextResponse } from 'next/server';
import fs from 'fs';
import path from 'path';

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const format = searchParams.get('format') || 'apk';

  const isAab = format.toLowerCase() === 'aab';
  const fileName = isAab ? 'Atiku2027_Situation_Room.aab' : 'Atiku2027_Situation_Room.apk';
  const contentType = isAab
    ? 'application/octet-stream'
    : 'application/vnd.android.package-archive';

  const possiblePaths = isAab
    ? [
        path.join(process.cwd(), 'public', 'downloads', 'Atiku2027_Situation_Room.aab'),
        path.join(process.cwd(), 'android', 'app', 'build', 'outputs', 'app-release.aab'),
        '/Users/user/Downloads/atiku2027.getocore.ng - Google Play Package/ATIKU2027/Presidential Situation Room 2027.aab'
      ]
    : [
        path.join(process.cwd(), 'public', 'downloads', 'Atiku2027_Situation_Room.apk'),
        path.join(process.cwd(), 'android', 'app', 'build', 'outputs', 'apk', 'release', 'app-release-signed.apk'),
        path.join(process.cwd(), 'public', 'downloads', 'Atiku2027.apk'),
        '/Users/user/Downloads/atiku2027.getocore.ng - Google Play Package/ATIKU2027/Presidential Situation Room 2027.apk'
      ];

  let filePath: string | null = null;
  for (const p of possiblePaths) {
    if (fs.existsSync(p)) {
      filePath = p;
      break;
    }
  }

  if (!filePath) {
    return NextResponse.json({ error: `${isAab ? 'AAB' : 'APK'} package not found on server` }, { status: 404 });
  }

  const stat = fs.statSync(filePath);
  const fileBuffer = fs.readFileSync(filePath);

  return new NextResponse(fileBuffer, {
    status: 200,
    headers: {
      'Content-Type': contentType,
      'Content-Length': stat.size.toString(),
      'Content-Disposition': `attachment; filename="${fileName}"`,
      'Cache-Control': 'public, max-age=3600'
    }
  });
}
