"use client";

import { z } from "zod";

import { Result, type Result as ResultT, SpAsyncUtil } from "@/utils";

import { StorageKeys } from "../storage_keys";

const PendingPaymentOrderSchema = z.object({
  orderId: z.string().min(1),
  payChannel: z.literal("ezpay"),
  subscriptionType: z.enum(["vip", "topup"]),
  returnTo: z.enum(["chat"]).optional(),
  createdAt: z.number(),
});

export type PendingPaymentOrder = z.output<typeof PendingPaymentOrderSchema>;

export class PendingPaymentOrderStorage {
  private constructor() {}

  static setPendingOrder(
    order: PendingPaymentOrder,
  ): Promise<ResultT<void>> {
    return SpAsyncUtil.setJson(
      StorageKeys.pendingPaymentOrder,
      order,
      PendingPaymentOrderSchema,
    );
  }

  static getPendingOrder(): Promise<ResultT<PendingPaymentOrder | null>> {
    return SpAsyncUtil.getJson(
      StorageKeys.pendingPaymentOrder,
      PendingPaymentOrderSchema,
    );
  }

  static async getPendingOrderForType(
    subscriptionType: PendingPaymentOrder["subscriptionType"],
  ): Promise<ResultT<PendingPaymentOrder | null>> {
    const result = await PendingPaymentOrderStorage.getPendingOrder();
    if (Result.isErr(result)) return result;
    if (result.data?.subscriptionType !== subscriptionType) {
      return Result.ok(null);
    }
    return result;
  }

  static clearPendingOrder(): Promise<ResultT<void>> {
    return SpAsyncUtil.remove(StorageKeys.pendingPaymentOrder);
  }
}
