import { error, json } from "@sveltejs/kit";
import { MAX_SATS_RECEIVE, MIN_SATS_RECEIVE } from "$lib/config";
import {
  getUser,
  isNpub,
  userExistsOrNpub,
  validateLightningInvoiceAmount,
} from "$lib";

/** @type {import('./$types').RequestHandler} */
export async function GET({ params, url }) {
  const { username } = params;
  const amount = url.searchParams.get("amount");

  if (!username || !amount) {
    throw error(400, "User and amount parameters are required");
  }

  if (!/^[a-z0-9\-_]+$/.test(username)) {
    throw error(400, "Invalid username format");
  }

  if (!(await userExistsOrNpub(username))) {
    throw error(404, "User not found");
  }

  if (
    !amount || !validateLightningInvoiceAmount(amount, { isMillisats: true })
  ) {
    throw error(
      400,
      `Amount must be between ${MIN_SATS_RECEIVE} and ${MAX_SATS_RECEIVE} millisats`,
    );
  }

  const user = isNpub(username) ? username : (await getUser(username))?.npub;

  if (!user) {
    throw error(404, "User not found");
  }

  const npubxRequest =
    `https://npubx.cash/.well-known/lnurlp/${user}?amount=${amount}`;

  const response = await fetch(npubxRequest);

  if (!response.ok) {
    throw error(500, "Failed to create swap");
  }

  const data = await response.json();

  return json(data);
}

export async function OPTIONS() {
  return new Response(null, {
    headers: {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "GET, OPTIONS",
      "Access-Control-Allow-Headers": "Content-Type",
    },
  });
}
