/**
 * WHMCS Subscriptions Provider - Raw Types
 *
 * Type definitions for the WHMCS subscriptions API contract:
 * - Request parameter types (API inputs)
 * - Response types (API outputs)
 */

import { z } from "zod";

import {
  whmcsString as s,
  whmcsNumberLike as numberLike,
  whmcsRequiredNumber as normalizeRequiredNumber,
  whmcsOptionalNumber as normalizeOptionalNumber,
} from "../../../common/providers/whmcs-utils/index.js";

const optionalStringField = () =>
  z
    .union([z.string(), z.number()])
    .optional()
    .nullable()
    .transform(value => {
      if (value === undefined || value === null) return;
      const text = String(value).trim();
      return text.length > 0 ? text : undefined;
    });

// ============================================================================
// Request Parameter Types
// ============================================================================

/**
 * Parameters for WHMCS GetClientsProducts API
 */
export interface WhmcsGetClientsProductsParams {
  clientid: number;
  serviceid?: number;
  pid?: number;
  domain?: string;
  limitstart?: number;
  limitnum?: number;
  orderby?: "id" | "productname" | "regdate" | "nextduedate";
  order?: "ASC" | "DESC";
  [key: string]: unknown;
}

// ============================================================================
// Response Types
// ============================================================================

// Custom field structure
export const whmcsCustomFieldSchema = z.object({
  id: z.number().optional(),
  name: z.string().optional(),
  value: z.string().optional(),
});

export const whmcsCustomFieldsContainerSchema = z.object({
  customfield: z.union([whmcsCustomFieldSchema, z.array(whmcsCustomFieldSchema)]),
});

export const whmcsConfigOptionSchema = z.object({
  id: normalizeOptionalNumber,
  option: s.optional(),
  type: s.optional(),
  value: s.optional(),
});

export const whmcsConfigOptionsContainerSchema = z.object({
  configoption: z.union([whmcsConfigOptionSchema, z.array(whmcsConfigOptionSchema)]),
});

// Raw WHMCS Product/Service (Subscription)
export const whmcsProductRawSchema = z.object({
  id: normalizeRequiredNumber,
  clientid: normalizeRequiredNumber,
  serviceid: normalizeOptionalNumber,
  qty: normalizeOptionalNumber,
  pid: normalizeOptionalNumber,
  orderid: normalizeOptionalNumber,
  ordernumber: optionalStringField(),
  regdate: s,
  name: s,
  translated_name: s.optional(),
  groupname: s.optional(),
  translated_groupname: s.optional(),
  domain: optionalStringField(),
  dedicatedip: optionalStringField(),
  serverid: normalizeOptionalNumber,
  servername: optionalStringField(),
  serverip: optionalStringField(),
  serverhostname: optionalStringField(),
  suspensionreason: s.optional(),
  promoid: normalizeOptionalNumber,
  subscriptionid: s.optional(),
  overideautosuspend: optionalStringField(),
  overidesuspenduntil: optionalStringField(),
  ns1: optionalStringField(),
  ns2: optionalStringField(),
  assignedips: optionalStringField(),

  // Pricing
  firstpaymentamount: numberLike.optional(),
  amount: numberLike.optional(),
  recurringamount: numberLike.optional(),
  billingcycle: s.optional(),
  paymentmethod: s.optional(),
  paymentmethodname: s.optional(),

  // Dates
  nextduedate: s.optional(),
  nextinvoicedate: s.optional(),

  // Status
  status: s,
  username: s.optional(),
  password: s.optional(),

  // Notes
  notes: s.optional(),
  diskusage: normalizeOptionalNumber,
  disklimit: normalizeOptionalNumber,
  bwusage: normalizeOptionalNumber,
  bwlimit: normalizeOptionalNumber,
  lastupdate: s.optional(),

  // Custom fields
  customfields: whmcsCustomFieldsContainerSchema.optional(),
  configoptions: whmcsConfigOptionsContainerSchema.optional(),

  // Pricing details
  pricing: z
    .object({
      amount: numberLike.optional(),
      currency: s.optional(),
      currencyprefix: s.optional(),
      currencysuffix: s.optional(),
    })
    .optional(),
});

export type WhmcsProductRaw = z.infer<typeof whmcsProductRawSchema>;
export type WhmcsCustomField = z.infer<typeof whmcsCustomFieldSchema>;

// ============================================================================
// WHMCS Product List Response (GetClientsProducts API)
// ============================================================================

/**
 * WHMCS GetClientsProducts API response schema
 */
const whmcsProductContainerSchema = z.object({
  product: z.preprocess(
    value => {
      if (value === null || value === undefined || value === "") {
        return;
      }
      return value;
    },
    z.union([whmcsProductRawSchema, z.array(whmcsProductRawSchema)]).optional()
  ),
});

export const whmcsProductListResponseSchema = z.object({
  result: z.enum(["success", "error"]).optional(),
  message: s.optional(),
  clientid: normalizeOptionalNumber,
  serviceid: normalizeOptionalNumber,
  pid: normalizeOptionalNumber,
  domain: s.nullable().optional(),
  totalresults: normalizeOptionalNumber,
  startnumber: normalizeOptionalNumber,
  numreturned: normalizeOptionalNumber,
  products: z.preprocess(value => {
    if (value === null || value === undefined) {
      return;
    }

    if (typeof value === "string") {
      return;
    }

    return value;
  }, whmcsProductContainerSchema.optional()),
});

export type WhmcsProductListResponse = z.infer<typeof whmcsProductListResponseSchema>;
