export type PaymentLinkStatus = "draft" | "active" | "paused" | "archived";
export type PaymentLinkType = "one_time" | "subscription";
export type PaymentLinkIntervalUnit = "days" | "months" | "years";

export type PaymentLinkRecord = {
  id: string;
  user_id: string;
  company_id: string | null;
  slug: string;
  code: string;
  status: PaymentLinkStatus;
  type: PaymentLinkType;
  title: string;
  description: string | null;
  amount: number | string | null;
  currency: string | null;
  image_url: string | null;
  interval_count: number | null;
  interval_unit: PaymentLinkIntervalUnit | null;
  allow_credit_card: boolean | null;
  allow_pix: boolean | null;
  allow_boleto: boolean | null;
  checkout_config: Record<string, unknown> | null;
  share_config: Record<string, unknown> | null;
  metadata: Record<string, unknown> | null;
  last_paid_at: string | null;
  last_opened_at: string | null;
  expires_at: string | null;
  created_at: string;
  updated_at: string;
};

export type PaymentLinkPublicData = {
  id: string;
  userId: string;
  slug: string;
  code: string;
  status: PaymentLinkStatus;
  type: PaymentLinkType;
  title: string;
  description: string;
  amount: number;
  currency: string;
  imageUrl: string;
  intervalCount: number | null;
  intervalUnit: PaymentLinkIntervalUnit | null;
  allowCreditCard: boolean;
  allowPix: boolean;
  allowBoleto: boolean;
  checkoutConfig: Record<string, unknown>;
  shareConfig: Record<string, unknown>;
  metadata: Record<string, unknown>;
  expiresAt: string | null;
};

export type PaymentLinkGuestProfile = {
  name: string;
  email: string;
  document: string;
  phone: string;
};

export function normalizeText(value: unknown) {
  return String(value || "").trim();
}

export function normalizeMoney(value: unknown) {
  const numeric = Number(value);
  if (!Number.isFinite(numeric)) return 0;
  return Number(numeric.toFixed(2));
}

export function normalizeIntervalUnit(value: unknown): PaymentLinkIntervalUnit | null {
  return value === "days" || value === "months" || value === "years" ? value : null;
}

export function mapPaymentLinkRecord(row: PaymentLinkRecord): PaymentLinkPublicData {
  return {
    id: row.id,
    userId: row.user_id,
    slug: normalizeText(row.slug),
    code: normalizeText(row.code),
    status: row.status,
    type: row.type,
    title: normalizeText(row.title),
    description: normalizeText(row.description),
    amount: normalizeMoney(row.amount),
    currency: normalizeText(row.currency) || "BRL",
    imageUrl: normalizeText(row.image_url),
    intervalCount: typeof row.interval_count === "number" ? row.interval_count : Number(row.interval_count || 0) || null,
    intervalUnit: normalizeIntervalUnit(row.interval_unit),
    allowCreditCard: row.allow_credit_card !== false,
    allowPix: row.allow_pix !== false,
    allowBoleto: row.allow_boleto === true,
    checkoutConfig: row.checkout_config || {},
    shareConfig: row.share_config || {},
    metadata: row.metadata || {},
    expiresAt: normalizeText(row.expires_at) || null,
  };
}

export function normalizeGuestProfile(input: Record<string, unknown> | null | undefined): PaymentLinkGuestProfile {
  return {
    name: normalizeText(input?.name),
    email: normalizeText(input?.email),
    document: normalizeText(input?.document).replace(/\D/g, "").slice(0, 14),
    phone: normalizeText(input?.phone),
  };
}

export function getMissingGuestFields(profile: PaymentLinkGuestProfile) {
  const missing: string[] = [];
  if (!profile.name) missing.push("Nome");
  if (!profile.email) missing.push("E-mail");
  if (!profile.document) missing.push("CPF/CNPJ");
  if (!profile.phone) missing.push("Telefone");
  return missing;
}

export function paymentLinkRecurrenceLabel(link: PaymentLinkPublicData) {
  if (link.type !== "subscription" || !link.intervalCount || !link.intervalUnit) return "Pagamento único";
  if (link.intervalUnit === "days") {
    return link.intervalCount === 1 ? "Cobrança diária" : `A cada ${link.intervalCount} dias`;
  }
  if (link.intervalUnit === "years") {
    return link.intervalCount === 1 ? "Cobrança anual" : `A cada ${link.intervalCount} anos`;
  }
  return link.intervalCount === 1 ? "Cobrança mensal" : `A cada ${link.intervalCount} meses`;
}

export function normalizeMercadoPagoSubscriptionStatus(value: unknown) {
  const status = normalizeText(value).toLowerCase();
  if (status === "authorized") return "authorized";
  if (status === "paused") return "paused";
  if (status === "cancelled" || status === "canceled") return "cancelled";
  if (status === "finished") return "finished";
  if (status === "rejected") return "rejected";
  return "pending";
}
