import {
  ORDER_TYPE,
  buildOrderConfigurations,
  normalizeOrderSelections,
  type OrderConfigurations,
  type OrderSelections,
  type OrderTypeValue,
} from "@customer-portal/domain/orders";

export interface CheckoutParamsSnapshot {
  orderType: OrderTypeValue;
  selections: OrderSelections;
  configuration?: OrderConfigurations;
  planReference: string | null;
  warnings: string[];
}

export class CheckoutParamsService {
  private static toRecord(params: URLSearchParams): Record<string, string> {
    const record: Record<string, string> = {};
    params.forEach((value, key) => {
      if (key !== "type") {
        record[key] = value;
      }
    });
    return record;
  }

  static resolveOrderType(params: URLSearchParams): OrderTypeValue {
    const type = params.get("type")?.toLowerCase();
    switch (type) {
      case "sim":
        return ORDER_TYPE.SIM;
      case "vpn":
        return ORDER_TYPE.VPN;
      case "other":
        return ORDER_TYPE.OTHER;
      case "internet":
      default:
        return ORDER_TYPE.INTERNET;
    }
  }

  private static coalescePlanReference(selections: OrderSelections): string | null {
    // After cleanup, we only use planSku
    const planSku = selections.planSku;
    if (typeof planSku === "string" && planSku.trim().length > 0) {
      return planSku.trim();
    }
    return null;
  }

  static buildSnapshot(params: URLSearchParams): CheckoutParamsSnapshot {
    const orderType = this.resolveOrderType(params);
    const rawRecord = this.toRecord(params);
    const warnings: string[] = [];

    let selections: OrderSelections;
    try {
      selections = normalizeOrderSelections(rawRecord);
    } catch (error) {
      warnings.push(
        error instanceof Error ? error.message : "Failed to normalize checkout selections"
      );
      selections = rawRecord as unknown as OrderSelections;
    }

    let configuration: OrderConfigurations | undefined;
    try {
      configuration = buildOrderConfigurations(selections);
    } catch (error) {
      warnings.push(
        error instanceof Error ? error.message : "Failed to derive order configuration"
      );
    }

    const planReference = this.coalescePlanReference(selections);

    return {
      orderType,
      selections,
      configuration,
      planReference,
      warnings,
    };
  }
}
