import type { Route } from './+types/proxy'

// Mapping of extensions to MIME types
const mimeTypes: Record<string, string> = {
  // Images
  '.jpg': 'image/jpeg',
  '.jpeg': 'image/jpeg',
  '.png': 'image/png',
  '.gif': 'image/gif',
  '.webp': 'image/webp',
  '.svg': 'image/svg+xml',

  // Fonts
  '.woff': 'font/woff',
  '.woff2': 'font/woff2',
  '.ttf': 'font/ttf',
  '.otf': 'font/otf',
  '.eot': 'application/vnd.ms-fontobject',

  // Others
  '.js': 'application/javascript',
  '.css': 'text/css',
  '.html': 'text/html',
  '.json': 'application/json'
}

export async function loader({ params, context }: Route.LoaderArgs) {
  const bucketEndpoint = context.cloudflare.env.BUCKET_ENDPOINT
  const bucketName = context.cloudflare.env.BUCKET_NAME
  const param = params['*'] ?? ''
  const url = new URL(`${bucketName}/scorm/${param}`, bucketEndpoint)
  const upstream = await fetch(url.toString())

  const ext = param.substring(param.lastIndexOf('.')).toLowerCase()
  const contentType =
    mimeTypes[ext] ||
    upstream.headers.get('Content-Type') ||
    'application/octet-stream'

  const headers = new Headers(upstream.headers)
  headers.set('Content-Type', contentType)

  // Essential headers for fonts
  if (contentType.includes('font')) {
    headers.set('Access-Control-Allow-Methods', 'GET')
    headers.set('Access-Control-Allow-Headers', 'Content-Type')
    headers.set('Vary', 'Origin')
  }

  // Direct streaming for binaries (images, fonts, etc.)
  if (
    contentType.startsWith('image/') ||
    contentType.includes('font') ||
    contentType === 'application/octet-stream'
  ) {
    return new Response(upstream.body, {
      status: upstream.status,
      headers
    })
  }

  return new Response(await upstream.text(), {
    status: upstream.status,
    headers
  })
}
