export type MailMaliPlanCode = "starter" | "professional" | "business";

export type MailMaliServiceStatus =
  | "active"
  | "renewal_due_60_days"
  | "renewal_due_30_days"
  | "renewal_due_7_days"
  | "past_due"
  | "grace_period"
  | "payment_pending"
  | "payment_failed"
  | "suspended"
  | "reactivation_pending"
  | "cancelled"
  | "terminated";

export type MailMaliMockServiceScenario =
  | "active"
  | "renewal_due_30_days"
  | "past_due"
  | "grace_period"
  | "suspended"
  | "reactivation_pending";

export type MailMaliAllowedAction =
  | "create_mailbox"
  | "order_more_mailboxes"
  | "view_mailboxes"
  | "view_security_status"
  | "view_google_connect"
  | "view_mail_protection"
  | "view_custom_hostnames";

export type MailMaliApiErrorReasonCode =
  | "bap_unavailable"
  | "domain_not_found"
  | "subscription_inactive"
  | "quota_stale"
  | "payment_pending"
  | "payment_failed"
  | "quota_full"
  | "selected_plan_unavailable"
  | "domain_suspended"
  | "provisioning_unavailable"
  | "unexpected_response"
  | "unknown";

export type MailMaliPlanQuotaRow = {
  plan_id: string;
  plan_code: MailMaliPlanCode;
  display_name: string;
  storage_gb: number;
  annual_price_thb: number;
  paid: number;
  used: number;
  reserved: number;
  available: number;
  subscription_id: string;
  term_start: string;
  term_end: string;
  renewal_date: string;
  service_status: MailMaliServiceStatus;
  allowed_actions: MailMaliAllowedAction[];
  payment_url?: string | null;
  quota_version: string;
  generated_at: string;
};

export type MailMaliQuotaResponse = {
  domain: string;
  service_status: MailMaliServiceStatus;
  allowed_actions: MailMaliAllowedAction[];
  payment_url?: string | null;
  quota_version: string;
  generated_at: string;
  plans: MailMaliPlanQuotaRow[];
};

export type MailMaliMailboxStatus = "active" | "suspended" | "pending" | "failed";

export type MailMaliMailboxAccountSummary = {
  mailbox_id: string;
  email: string;
  display_name: string;
  plan_id: string;
  plan_code: MailMaliPlanCode;
  plan_display_name: string;
  storage_gb: number;
  storage_used_gb?: number;
  status: MailMaliMailboxStatus;
  allowed_actions: MailMaliAllowedAction[];
};

export type MailMaliAddonOrderStatus = "draft" | "pending" | "paid" | "failed" | "cancelled" | "expired";

export type MailMaliAddonOrderSummary = {
  order_id: string;
  domain: string;
  plan_id: string;
  plan_code: MailMaliPlanCode;
  quantity: number;
  status: MailMaliAddonOrderStatus;
  payment_status: "not_required" | "pending" | "paid" | "failed";
  payment_url?: string | null;
  created_at: string;
  updated_at: string;
};

export type MailMaliSecurityStatusSummary = {
  domain: string;
  mail_protection_status: "healthy" | "degraded" | "unavailable";
  quarantine_count: number;
  dns_status: "ok" | "action_needed" | "checking";
  google_connect_status: "connected" | "needs_attention" | "not_connected";
  generated_at: string;
};

export type MailMaliQuarantineCategory = "spam" | "phishing" | "malware" | "policy";

export type MailMaliQuarantineStatus = "held" | "release_recorded" | "delete_recorded";

export type MailMaliQuarantineSeverity = "low" | "medium" | "high" | "critical";

export type MailMaliQuarantineAction = "release_message" | "delete_message";

export type MailMaliMailProtectionHealth = "healthy" | "degraded" | "unavailable";

export type MailMaliCustomHostnameStatus = "active" | "pending" | "action_needed" | "checking" | "failed";

export type MailMaliCustomHostnameDnsRecord = {
  type: "CNAME" | "TXT" | "MX" | "A" | "AAAA";
  name: string;
  value: string;
  status: "ok" | "missing" | "mismatch" | "checking";
};

export type MailMaliCustomHostnameSummary = {
  hostname: string;
  hostname_type?: string | null;
  status?: MailMaliCustomHostnameStatus;
  setup_status?: MailMaliCustomHostnameStatus;
  customer_message_en?: string | null;
  dns_status?: "ok" | "action_needed" | "checking" | "failed";
  ssl_status?: "active" | "pending" | "action_needed" | "checking" | "failed";
  target_hostname?: string | null;
  target_cname?: string | null;
  setup_url?: string | null;
  last_checked_at?: string | null;
  records?: MailMaliCustomHostnameDnsRecord[];
};

export type MailMaliCustomHostnameResponse = {
  domain: string;
  generated_at: string;
  hostnames: MailMaliCustomHostnameSummary[];
};

export type MailMaliQuarantinedMessageSummary = {
  message_id: string;
  recipient: string;
  sender: string;
  subject: string;
  received_at: string;
  category: MailMaliQuarantineCategory;
  status: MailMaliQuarantineStatus;
  score: number;
  severity: MailMaliQuarantineSeverity;
  allowed_actions: MailMaliQuarantineAction[];
};

export type MailMaliApiError = {
  reason_code: MailMaliApiErrorReasonCode;
  message: string;
  retryable: boolean;
  generated_at: string;
};

export type MailMaliCreateMailboxDraft = {
  local_part: string;
  display_name: string;
  plan_code: MailMaliPlanCode;
};

export type MailMaliBapReadonlyConfig = {
  enabled: boolean;
  baseUrl: string | null;
};

export class MailMaliBapReadonlyError extends Error {
  reasonCode: MailMaliApiErrorReasonCode;

  constructor(reasonCode: MailMaliApiErrorReasonCode, message = "Account data is temporarily unavailable. Please try again later or contact support.") {
    super(message);
    this.name = "MailMaliBapReadonlyError";
    this.reasonCode = reasonCode;
  }
}

export const mailMaliAccountDataUnavailableMessage = "Account data is temporarily unavailable. Please try again later or contact support.";

export function getMailMaliBapReadonlyConfig(): MailMaliBapReadonlyConfig {
  const enabled = (process.env.NEXT_PUBLIC_MAILMALI_BAP_READONLY_API_ENABLED || "false").trim().toLowerCase() === "true";
  const baseUrl = (process.env.NEXT_PUBLIC_MAILMALI_BAP_API_BASE_URL || "").trim().replace(/\/+$/, "");
  return {
    enabled: Boolean(enabled && baseUrl),
    baseUrl: baseUrl || null,
  };
}

function buildReadonlyEndpoint(config: MailMaliBapReadonlyConfig, domain: string, suffix: "quota" | "mailboxes" | "hostnames") {
  if (!config.enabled || !config.baseUrl) {
    throw new MailMaliBapReadonlyError("bap_unavailable");
  }
  const normalizedDomain = encodeURIComponent(domain.trim().toLowerCase());
  return `${config.baseUrl}/api/customer/domains/${normalizedDomain}/${suffix}`;
}

function reasonCodeFromStatus(status: number): MailMaliApiErrorReasonCode {
  if (status === 404) return "domain_not_found";
  if (status === 402 || status === 409 || status === 423) return "subscription_inactive";
  if (status >= 500) return "bap_unavailable";
  return "unexpected_response";
}

function isQuotaResponse(value: unknown): value is MailMaliQuotaResponse {
  return Boolean(value && typeof value === "object" && Array.isArray((value as MailMaliQuotaResponse).plans));
}

function isMailboxList(value: unknown): value is MailMaliMailboxAccountSummary[] {
  return Array.isArray(value);
}

function isHostnameResponse(value: unknown): value is MailMaliCustomHostnameResponse {
  return Boolean(value && typeof value === "object" && Array.isArray((value as MailMaliCustomHostnameResponse).hostnames));
}

function normalizeHostnameStatus(value: unknown, fallback: MailMaliCustomHostnameStatus = "checking"): MailMaliCustomHostnameStatus {
  if (value === "active" || value === "pending" || value === "action_needed" || value === "checking" || value === "failed") return value;
  return fallback;
}

export function buildMailMaliHostnameRecordFallback(hostname: string, targetCname?: string | null): MailMaliCustomHostnameDnsRecord[] {
  void hostname;
  return [
    {
      type: "CNAME",
      name: "mail",
      value: targetCname || "mail.mailmali.com",
      status: "checking",
    },
  ];
}

export function normalizeMailMaliCustomHostnameResponse(payload: MailMaliCustomHostnameResponse): MailMaliCustomHostnameResponse {
  return {
    domain: payload.domain,
    generated_at: payload.generated_at,
    hostnames: payload.hostnames.map((hostname) => {
      const targetCname = hostname.target_cname ?? hostname.target_hostname ?? "mail.mailmali.com";
      const setupStatus = normalizeHostnameStatus(hostname.setup_status ?? hostname.status);
      return {
        ...hostname,
        status: normalizeHostnameStatus(hostname.status ?? hostname.setup_status, setupStatus),
        setup_status: setupStatus,
        dns_status: hostname.dns_status ?? "checking",
        ssl_status: hostname.ssl_status ?? "checking",
        target_cname: targetCname,
        target_hostname: hostname.target_hostname ?? targetCname,
        records: hostname.records?.length ? hostname.records : buildMailMaliHostnameRecordFallback(hostname.hostname, targetCname),
      };
    }),
  };
}

export async function fetchMailMaliQuota(domain: string, config = getMailMaliBapReadonlyConfig()): Promise<MailMaliQuotaResponse> {
  const response = await fetch(buildReadonlyEndpoint(config, domain, "quota"), { method: "GET", cache: "no-store" });
  if (!response.ok) {
    throw new MailMaliBapReadonlyError(reasonCodeFromStatus(response.status));
  }
  const payload: unknown = await response.json();
  if (!isQuotaResponse(payload)) {
    throw new MailMaliBapReadonlyError("unexpected_response");
  }
  return payload;
}

export async function fetchMailMaliMailboxes(domain: string, config = getMailMaliBapReadonlyConfig()): Promise<MailMaliMailboxAccountSummary[]> {
  const response = await fetch(buildReadonlyEndpoint(config, domain, "mailboxes"), { method: "GET", cache: "no-store" });
  if (!response.ok) {
    throw new MailMaliBapReadonlyError(reasonCodeFromStatus(response.status));
  }
  const payload: unknown = await response.json();
  if (!isMailboxList(payload)) {
    throw new MailMaliBapReadonlyError("unexpected_response");
  }
  return payload;
}

export async function fetchMailMaliCustomHostnames(domain: string, config = getMailMaliBapReadonlyConfig()): Promise<MailMaliCustomHostnameResponse> {
  const response = await fetch(buildReadonlyEndpoint(config, domain, "hostnames"), { method: "GET", cache: "no-store" });
  if (!response.ok) {
    throw new MailMaliBapReadonlyError(reasonCodeFromStatus(response.status));
  }
  const payload: unknown = await response.json();
  if (!isHostnameResponse(payload)) {
    throw new MailMaliBapReadonlyError("unexpected_response");
  }
  return normalizeMailMaliCustomHostnameResponse(payload);
}

const generatedAt = "2026-09-01T10:00:00Z";

export const mockMailMaliQuotaResponse: MailMaliQuotaResponse = {
  domain: "mail.example.com",
  service_status: "renewal_due_30_days",
  allowed_actions: ["create_mailbox", "order_more_mailboxes", "view_mailboxes", "view_security_status", "view_google_connect", "view_mail_protection", "view_custom_hostnames"],
  payment_url: null,
  quota_version: "quota_20260901_001",
  generated_at: generatedAt,
  plans: [
    {
      plan_id: "plan_starter_001",
      plan_code: "starter",
      display_name: "Starter",
      storage_gb: 5,
      annual_price_thb: 600,
      paid: 25,
      used: 18,
      reserved: 1,
      available: 6,
      subscription_id: "sub_example_2026",
      term_start: "2026-01-01",
      term_end: "2026-12-31",
      renewal_date: "2026-12-31",
      service_status: "renewal_due_30_days",
      allowed_actions: ["create_mailbox", "order_more_mailboxes"],
      payment_url: null,
      quota_version: "quota_20260901_001",
      generated_at: generatedAt,
    },
    {
      plan_id: "plan_professional_001",
      plan_code: "professional",
      display_name: "Professional",
      storage_gb: 15,
      annual_price_thb: 1200,
      paid: 10,
      used: 6,
      reserved: 0,
      available: 4,
      subscription_id: "sub_example_2026",
      term_start: "2026-01-01",
      term_end: "2026-12-31",
      renewal_date: "2026-12-31",
      service_status: "renewal_due_30_days",
      allowed_actions: ["create_mailbox", "order_more_mailboxes"],
      payment_url: null,
      quota_version: "quota_20260901_001",
      generated_at: generatedAt,
    },
    {
      plan_id: "plan_business_001",
      plan_code: "business",
      display_name: "Business",
      storage_gb: 50,
      annual_price_thb: 2400,
      paid: 5,
      used: 5,
      reserved: 0,
      available: 0,
      subscription_id: "sub_example_2026",
      term_start: "2026-01-01",
      term_end: "2026-12-31",
      renewal_date: "2026-12-31",
      service_status: "renewal_due_30_days",
      allowed_actions: ["order_more_mailboxes"],
      payment_url: null,
      quota_version: "quota_20260901_001",
      generated_at: generatedAt,
    },
  ],
};

const mockScenarioStatus: Record<MailMaliMockServiceScenario, MailMaliServiceStatus> = {
  active: "active",
  renewal_due_30_days: "renewal_due_30_days",
  past_due: "past_due",
  grace_period: "grace_period",
  suspended: "suspended",
  reactivation_pending: "reactivation_pending",
};

export const mockMailMaliServiceScenarios: Array<{ value: MailMaliMockServiceScenario; label: string }> = [
  { value: "active", label: "Active" },
  { value: "renewal_due_30_days", label: "Renewal due in 30 days" },
  { value: "past_due", label: "Past due" },
  { value: "grace_period", label: "Grace period" },
  { value: "suspended", label: "Suspended" },
  { value: "reactivation_pending", label: "Service restore pending" },
];

export function isMailMaliServiceRestorePending(status: MailMaliServiceStatus) {
  return status === "reactivation_pending";
}

export function buildMockMailMaliQuotaResponse(scenario: MailMaliMockServiceScenario = "renewal_due_30_days"): MailMaliQuotaResponse {
  const serviceStatus = mockScenarioStatus[scenario];
  const paymentUrl = null;
  const allowedActions: MailMaliAllowedAction[] = serviceStatus === "suspended" || serviceStatus === "cancelled" || serviceStatus === "terminated"
    ? ["order_more_mailboxes", "view_mailboxes", "view_security_status"]
    : ["create_mailbox", "order_more_mailboxes", "view_mailboxes", "view_security_status", "view_google_connect", "view_mail_protection", "view_custom_hostnames"];
  return {
    ...mockMailMaliQuotaResponse,
    service_status: serviceStatus,
    allowed_actions: allowedActions,
    payment_url: paymentUrl,
    plans: mockMailMaliQuotaResponse.plans.map((plan) => ({
      ...plan,
      service_status: serviceStatus,
      allowed_actions: plan.available > 0 && allowedActions.includes("create_mailbox") ? ["create_mailbox", "order_more_mailboxes"] : ["order_more_mailboxes"],
      payment_url: plan.available <= 0 ? plan.payment_url : paymentUrl,
    })),
  };
}

export const mockMailMaliMailboxes: MailMaliMailboxAccountSummary[] = [
  {
    mailbox_id: "mbx_alex",
    email: "alex@example.com",
    display_name: "Alex Rivera",
    plan_id: "plan_starter_001",
    plan_code: "starter",
    plan_display_name: "Starter",
    storage_gb: 5,
    storage_used_gb: 2.1,
    status: "active",
    allowed_actions: ["view_mailboxes"],
  },
  {
    mailbox_id: "mbx_billing",
    email: "billing@example.com",
    display_name: "Billing Team",
    plan_id: "plan_professional_001",
    plan_code: "professional",
    plan_display_name: "Professional",
    storage_gb: 15,
    storage_used_gb: 7.4,
    status: "active",
    allowed_actions: ["view_mailboxes"],
  },
  {
    mailbox_id: "mbx_ops",
    email: "ops@example.com",
    display_name: "Operations",
    plan_id: "plan_business_001",
    plan_code: "business",
    plan_display_name: "Business",
    storage_gb: 50,
    storage_used_gb: 18.6,
    status: "active",
    allowed_actions: ["view_mailboxes"],
  },
];

export const mockMailMaliAddonOrders: MailMaliAddonOrderSummary[] = [
  {
    order_id: "order_business_001",
    domain: "mail.example.com",
    plan_id: "plan_business_001",
    plan_code: "business",
    quantity: 5,
    status: "pending",
    payment_status: "pending",
    payment_url: null,
    created_at: "2026-09-01T09:00:00Z",
    updated_at: generatedAt,
  },
];

export const mockMailMaliSecurityStatus: MailMaliSecurityStatusSummary = {
  domain: "mail.example.com",
  mail_protection_status: "healthy",
  quarantine_count: 3,
  dns_status: "action_needed",
  google_connect_status: "needs_attention",
  generated_at: generatedAt,
};

export const mockMailMaliQuarantinedMessages: MailMaliQuarantinedMessageSummary[] = [
  {
    message_id: "qmsg_001",
    recipient: "alex@example.com",
    sender: "billing-notice@example.net",
    subject: "Invoice review requested",
    received_at: "2026-09-01T08:35:00Z",
    category: "spam",
    status: "held",
    score: 7.8,
    severity: "medium",
    allowed_actions: ["release_message", "delete_message"],
  },
  {
    message_id: "qmsg_002",
    recipient: "ops@example.com",
    sender: "security-alert@example.org",
    subject: "Unusual sign-in notice",
    received_at: "2026-09-01T07:12:00Z",
    category: "phishing",
    status: "held",
    score: 9.4,
    severity: "high",
    allowed_actions: ["delete_message"],
  },
  {
    message_id: "qmsg_003",
    recipient: "billing@example.com",
    sender: "files@example.net",
    subject: "Shared document waiting",
    received_at: "2026-08-31T16:50:00Z",
    category: "policy",
    status: "held",
    score: 5.6,
    severity: "low",
    allowed_actions: ["release_message", "delete_message"],
  },
];

export const mockMailMaliCustomHostnameResponse: MailMaliCustomHostnameResponse = {
  domain: "mail.example.com",
  generated_at: generatedAt,
  hostnames: [
    {
      hostname: "mail.example.com",
      status: "active",
      dns_status: "ok",
      ssl_status: "active",
      target_hostname: "mail.mailmali.com",
      target_cname: "mail.mailmali.com",
      setup_url: null,
      last_checked_at: generatedAt,
      records: [
        { type: "CNAME", name: "mail", value: "mail.mailmali.com", status: "ok" },
        { type: "TXT", name: "_mailmali.mail", value: "mailmali-site-verification=example", status: "ok" },
      ],
    },
    {
      hostname: "webmail.example.com",
      status: "action_needed",
      dns_status: "action_needed",
      ssl_status: "pending",
      target_hostname: "mail.mailmali.com",
      target_cname: "mail.mailmali.com",
      setup_url: null,
      last_checked_at: generatedAt,
      records: [
        { type: "CNAME", name: "webmail", value: "mail.mailmali.com", status: "missing" },
        { type: "TXT", name: "_mailmali.webmail", value: "mailmali-site-verification=example", status: "checking" },
      ],
    },
  ],
};

export function getMockMailMaliDomainAdminData(scenario: MailMaliMockServiceScenario = "renewal_due_30_days") {
  const quota = buildMockMailMaliQuotaResponse(scenario);
  const activeLike = scenario === "active" || isMailMaliServiceRestorePending(mockScenarioStatus[scenario]);
  return {
    quota,
    mailboxes: mockMailMaliMailboxes,
    addonOrders: activeLike ? [] : mockMailMaliAddonOrders,
    quarantinedMessages: mockMailMaliQuarantinedMessages,
    customHostnames: mockMailMaliCustomHostnameResponse,
    security: {
      ...mockMailMaliSecurityStatus,
      dns_status: activeLike ? "ok" : mockMailMaliSecurityStatus.dns_status,
      google_connect_status: activeLike ? "connected" : mockMailMaliSecurityStatus.google_connect_status,
      mail_protection_status: scenario === "suspended" ? "degraded" : mockMailMaliSecurityStatus.mail_protection_status,
    } satisfies MailMaliSecurityStatusSummary,
  };
}

export function buildMockMailMaliAddonOrderUrl(domain: string, planCode: MailMaliPlanCode) {
  void domain;
  void planCode;
  return "";
}
