import { createReadStream, existsSync, statSync } from 'node:fs';
import path from 'node:path';
import { Readable } from 'node:stream';

export const runtime = 'nodejs';

const APK_CANDIDATES = [
  process.env.TAURI_ANDROID_APK_PATH,
  path.resolve(process.cwd(), 'public/downloads/lendry-id.apk'),
  path.resolve(process.cwd(), 'apps/frontend/public/downloads/lendry-id.apk'),
  '/app/apps/frontend/public/downloads/lendry-id.apk',
  '/app/public/downloads/lendry-id.apk',
  path.resolve(process.cwd(), '../../tauri_app/src-tauri/gen/android/app/build/outputs/apk/universal/release/app-universal-release.apk'),
  path.resolve(process.cwd(), '../../tauri_app/src-tauri/gen/android/app/build/outputs/apk/universal/debug/app-universal-debug.apk'),
  path.resolve(process.cwd(), '../../tauri_app/src-tauri/gen/android/app/build/outputs/apk/arm64/release/app-arm64-release.apk'),
  path.resolve(process.cwd(), '../../tauri_app/src-tauri/gen/android/app/build/outputs/apk/arm64/debug/app-arm64-debug.apk')
].filter((candidate): candidate is string => Boolean(candidate));

function resolveApkPath() {
  return APK_CANDIDATES.find((candidate) => existsSync(candidate) && statSync(candidate).isFile());
}

export async function GET() {
  const apkPath = resolveApkPath();
  if (!apkPath) {
    return new Response(
      'APK ещё не собран. Запустите: docker compose up --build tauri-apk-builder. После сборки файл появится как apps/frontend/public/downloads/lendry-id.apk.',
      {
        status: 404,
        headers: {
          'Content-Type': 'text/plain; charset=utf-8',
          'Cache-Control': 'no-store'
        }
      },
    );
  }

  const stat = statSync(apkPath);
  const stream = Readable.toWeb(createReadStream(apkPath)) as ReadableStream;

  return new Response(stream, {
    headers: {
      'Content-Type': 'application/vnd.android.package-archive',
      'Content-Length': String(stat.size),
      'Content-Disposition': 'attachment; filename="lendry-id.apk"',
      'Cache-Control': 'no-store'
    }
  });
}
