// It's very important to specify the .js extension here, otherwise Vercel
// won't be able to import it (even though the file is named .ts).
// import { handler as globalHandler } from "./common/index.js";

import { Redis } from '@upstash/redis';

// This is a workaround for deploying in vercel, which forces us to use
// file-based routes in the /api folder. We just re-export the global handler
// from the `start.ts` file that we also use for local development.
//
// In vercel.json, we have a rewrite rule that rewrites /openai to /api/openai.
// Ths is necessary so that all requests under the /openai route go to this handler.

export const config = { runtime: 'edge' };

/** Minimal CORS helper (mirrors the request’s Origin if present). */
function corsHeaders(requestHeaders: Headers): Headers {
  const h = new Headers();
  h.set('Access-Control-Allow-Origin', requestHeaders.get('origin') ?? '*');
  h.set(
    'Access-Control-Allow-Headers',
    requestHeaders.get('access-control-request-headers') ??
      'content-type,authorization'
  );
  h.set(
    'Access-Control-Allow-Methods',
    requestHeaders.get('access-control-request-method') ?? 'POST,OPTIONS'
  );
  h.set('Access-Control-Max-Age', '86400');
  return h;
}

export default async function handler(req: Request): Promise<Response> {
  // 1️⃣  Handle CORS pre-flight locally.
  if (req.method === 'OPTIONS') {
    return new Response(null, {
      status: 204,
      headers: corsHeaders(req.headers),
    });
  }

  const key = process.env.UPSTASH_TOKEN;
  if (!key) {
    return new Response('Missing UPSTASH_TOKEN', { status: 500 });
  }

  const pathItems = req.url.split('/');
  const snapshotId = pathItems[pathItems.length - 1];

  const redis = new Redis({
    url: 'https://bold-slug-35019.upstash.io',
    token: process.env.UPSTASH_TOKEN,
  });

  const headers = corsHeaders(req.headers);
  headers.set('Content-Type', 'application/json');
  headers.set('Cache-Control', 'no-cache');
  headers.set('X-Accel-Buffering', 'no'); // disable Nginx buffering (proxy-friendly)

  if (req.method === 'POST') {
    const jsonPayload = await req.json();
    await redis.set(snapshotId, jsonPayload);
    return new Response(JSON.stringify({ success: true }), {
      status: 200,
      headers,
    });
  }

  if (req.method === 'GET') {
    const snapshot = await redis.get(snapshotId);
    if (!snapshot) {
      return new Response(
        JSON.stringify({ success: false, error: 'Not found' }),
        {
          status: 404,
          headers,
        }
      );
    }
    return new Response(JSON.stringify(snapshot), {
      status: 200,
      headers,
    });
  }

  return new Response('Method Not Allowed', { status: 405 });
}
