import { z } from "zod/v4";
import { fn } from "../utils/fn.js";
import { Polar as PolarSdk } from "@polar-sh/sdk";
import { type Customer } from "@polar-sh/sdk/models/components/customer.js";

export namespace Polar {
  export const client = new PolarSdk({
    accessToken: process.env.POLAR_API_KEY || "",
    server: process.env.APP_STAGE !== "production" ? "sandbox" : "production",
  });

  export const fromUserEmail = fn(z.email(), async (email) => {
    const customers = await client.customers.list({ email });

    if (customers.result.items.length === 0) {
      return await client.customers.create({ email });
    }
    return customers.result.items[0] as Customer;
  });
}
