import type { NextRequest } from 'next/server';

function resolveServerApiBase(request: NextRequest) {
  const internal = process.env.INTERNAL_API_URL?.replace(/\/$/, '');
  if (internal) return internal;
  return `${request.nextUrl.origin}/idp-api`;
}

const PASSTHROUGH_HEADERS = [
  'content-type',
  'content-length',
  'content-disposition',
  'x-release-version',
  'x-release-version-code',
  'x-release-sha256',
  'cache-control'
] as const;

export async function proxyReleaseDownload(
  request: NextRequest,
  platform: 'android' | 'windows',
  releaseId?: string
) {
  const apiBase = resolveServerApiBase(request);
  const path = releaseId
    ? `/releases/download/${platform}/${releaseId}`
    : `/releases/download/${platform}`;

  const upstream = await fetch(`${apiBase}${path}`, {
    method: 'GET',
    cache: 'no-store'
  });

  if (!upstream.ok) {
    const message = await upstream.text().catch(() => 'Файл релиза недоступен');
    return new Response(message, {
      status: upstream.status,
      headers: {
        'Content-Type': 'text/plain; charset=utf-8',
        'Cache-Control': 'no-store'
      }
    });
  }

  const headers = new Headers();
  for (const key of PASSTHROUGH_HEADERS) {
    const value = upstream.headers.get(key);
    if (value) headers.set(key, value);
  }

  return new Response(upstream.body, {
    status: upstream.status,
    headers
  });
}
