import {
  BadRequestException,
  Injectable,
  Logger,
  NotFoundException,
} from '@nestjs/common';
import { ModuleRef } from '@nestjs/core';
import { Delivery } from '@prisma/client';
import * as crypto from 'crypto';
import { PrismaService } from '../../prisma/prisma.service';
import { BusinessService } from '../business/business.service';
import { PaymentPollingService } from '../payments/payment-polling.service';
import { OrderEventsService } from '../commerce/services/order-events.service';
import { normalizePhoneNumber } from '../../common/utils/phone.util';
import {
  RoadrunnerClient,
  RoadrunnerConfig,
  RoadrunnerDelivery,
  RoadrunnerError,
} from './roadrunner.client';
import { GeocodingService, distanceKm } from './geocoding.service';

export type QuoteOutcome =
  | {
      ok: true;
      quoteId: string;
      fee: number; // major units, e.g. 15.40
      feeMinor: number;
      currency: string;
      distanceKm: number | null;
      expiresAt: string;
    }
  | {
      ok: false;
      reason:
        | 'not_configured'
        | 'out_of_area'
        | 'unserviceable'
        | 'invalid'
        | 'unavailable';
      message: string;
    };

// Statuses after which nothing more will happen to a delivery
const TERMINAL = ['delivered', 'cancelled', 'failed'];
// Statuses that mean we can (re)book a fresh delivery for the order
const REBOOKABLE = [
  'awaiting_booking',
  'booking_failed',
  'cancelled',
  'failed',
  'dispatch_failed',
];

const CUSTOMER_MESSAGES: Record<
  string,
  (d: Delivery, orderNumber: string) => string
> = {
  assigned: (d, n) =>
    `🧑 *Courier assigned — Order #${n}*\n\n${d.courierName ? `*${d.courierName}*` : 'A courier'} will collect your order shortly.` +
    (d.trackingUrl ? `\n\n📍 Track live: ${d.trackingUrl}` : ''),
  picked_up: (d, n) =>
    `📦 *Order #${n} collected*\n\nThe courier has picked up your order.` +
    (d.trackingUrl ? `\n\n📍 Track live: ${d.trackingUrl}` : ''),
  in_transit: (d, n) =>
    `🛣️ *Order #${n} is on the way!*` +
    (d.courierName
      ? `\n\nCourier: *${d.courierName}*${d.courierPhone ? ` (${d.courierPhone})` : ''}`
      : '') +
    (d.trackingUrl ? `\n\n📍 Track live: ${d.trackingUrl}` : ''),
  delivered: (_d, n) =>
    `✅ *Order #${n} delivered*\n\nThank you for shopping with us! Reply *menu* to shop again.`,
  failed: (_d, n) =>
    `⚠️ *Delivery attempt failed — Order #${n}*\n\nWe couldn't complete the delivery. Our team will contact you to rearrange.`,
  cancelled: (_d, n) =>
    `❌ *Delivery cancelled — Order #${n}*\n\nYour delivery was cancelled. Reply *support* if you need help.`,
};

@Injectable()
export class DeliveryService {
  private readonly logger = new Logger(DeliveryService.name);

  constructor(
    private readonly prisma: PrismaService,
    private readonly businessService: BusinessService,
    private readonly client: RoadrunnerClient,
    private readonly geocoder: GeocodingService,
    private readonly moduleRef: ModuleRef,
  ) {}

  // ── Configuration ──────────────────────────────────────────────────────────

  /** Per-business credentials (BusinessIntegration 'roadrunner') override the ROADRUNNER_* env defaults. */
  async getConfig(businessId: string): Promise<RoadrunnerConfig | null> {
    const creds = ((await this.businessService.getDecryptedCredentials(
      businessId,
      'roadrunner',
    )) || {}) as Record<string, any>;
    const num = (v: unknown) =>
      v === undefined || v === null || v === '' ? undefined : Number(v);

    const cfg: RoadrunnerConfig = {
      baseUrl:
        creds.baseUrl ||
        process.env.ROADRUNNER_BASE_URL ||
        'https://staging.roadrunnerzw.com/api',
      keyId: creds.keyId || process.env.ROADRUNNER_KEY_ID || '',
      secret: creds.secret || process.env.ROADRUNNER_SECRET || '',
      webhookSecret:
        creds.webhookSecret || process.env.ROADRUNNER_WEBHOOK_SECRET,
      pickupAddress:
        creds.pickupAddress || process.env.ROADRUNNER_PICKUP_ADDRESS,
      pickupLocationId:
        creds.pickupLocationId || process.env.ROADRUNNER_PICKUP_LOCATION_ID,
      depotLat: num(creds.depotLat ?? process.env.ROADRUNNER_DEPOT_LAT),
      depotLng: num(creds.depotLng ?? process.env.ROADRUNNER_DEPOT_LNG),
      maxRadiusKm: num(
        creds.maxRadiusKm ?? process.env.ROADRUNNER_MAX_RADIUS_KM,
      ),
    };
    return cfg.keyId && cfg.secret ? cfg : null;
  }

  async isEnabled(businessId: string) {
    return !!(await this.getConfig(businessId));
  }

  async getStatus(businessId: string) {
    const cfg = await this.getConfig(businessId);
    if (!cfg) return { configured: false, connected: false };
    try {
      const ping = await this.client.ping(cfg);
      return {
        configured: true,
        connected: !!ping.ok,
        client: ping.client,
        scopes: Array.isArray(ping.scopes) ? ping.scopes : [],
        testMode: ping.test_mode === true || ping.test_mode === 'true',
        environment: new URL(cfg.baseUrl).hostname,
        pickupAddress: cfg.pickupAddress || null,
        maxRadiusKm: cfg.maxRadiusKm ?? null,
      };
    } catch (err: any) {
      return {
        configured: true,
        connected: false,
        error: err.message,
        environment: new URL(cfg.baseUrl).hostname,
      };
    }
  }

  // ── Quotes (used by the WhatsApp checkout) ─────────────────────────────────

  async quote(
    businessId: string,
    input: {
      address: string;
      lat?: number | null;
      lng?: number | null;
      phone?: string;
      itemsValue?: number;
    },
  ): Promise<QuoteOutcome> {
    const cfg = await this.getConfig(businessId);
    if (!cfg)
      return {
        ok: false,
        reason: 'not_configured',
        message: 'Home delivery is not configured.',
      };

    if (
      input.lat != null &&
      input.lng != null &&
      cfg.depotLat != null &&
      cfg.depotLng != null &&
      cfg.maxRadiusKm
    ) {
      const km = distanceKm(cfg.depotLat, cfg.depotLng, input.lat, input.lng);
      if (km > cfg.maxRadiusKm) {
        return {
          ok: false,
          reason: 'out_of_area',
          message: `That location is ${km.toFixed(0)} km from our depot. Home delivery currently covers up to ${cfg.maxRadiusKm} km around Harare.`,
        };
      }
    }

    try {
      const q = await this.client.createQuote(cfg, {
        ...this.pickupFields(cfg),
        dropoff: {
          address: input.address.slice(0, 512),
          phone: this.toE164(input.phone),
        },
        items_value:
          input.itemsValue != null ? Math.round(input.itemsValue * 100) : null,
      });
      if (!q.serviceable) {
        return {
          ok: false,
          reason: 'unserviceable',
          message: 'Sorry, our courier does not deliver to that address yet.',
        };
      }
      return {
        ok: true,
        quoteId: q.id,
        fee: q.delivery_fee.amount / 100,
        feeMinor: q.delivery_fee.amount,
        currency: q.delivery_fee.currency,
        distanceKm:
          q.distance_metres != null
            ? Math.round(q.distance_metres / 100) / 10
            : null,
        expiresAt: q.expires_at,
      };
    } catch (err: any) {
      if (err instanceof RoadrunnerError && err.status === 422) {
        return { ok: false, reason: 'invalid', message: err.message };
      }
      this.logger.error(`Road Runner quote failed: ${err.message}`);
      return {
        ok: false,
        reason: 'unavailable',
        message: 'Delivery pricing is temporarily unavailable.',
      };
    }
  }

  // ── Delivery lifecycle ─────────────────────────────────────────────────────

  /** Record the delivery details captured at checkout; booked with the courier once the order is paid. */
  async createDraft(
    businessId: string,
    orderId: string,
    d: {
      address?: string;
      lat?: number | null;
      lng?: number | null;
      quoteId?: string;
      feeMinor?: number;
      currency?: string;
      distanceKm?: number | null;
    },
  ) {
    return this.prisma.delivery.upsert({
      where: { orderId },
      create: {
        businessId,
        orderId,
        dropoffAddress: d.address,
        dropoffLat: d.lat ?? null,
        dropoffLng: d.lng ?? null,
        quoteId: d.quoteId,
        feeAmount: d.feeMinor,
        currency: d.currency || 'USD',
        distanceMetres:
          d.distanceKm != null ? Math.round(d.distanceKm * 1000) : null,
      },
      update: {},
    });
  }

  async bookForOrder(businessId: string, orderId: string) {
    const order = await this.prisma.order.findFirst({
      where: { id: orderId, businessId },
      include: { items: true, delivery: true, business: true },
    });
    if (!order) throw new NotFoundException('Order not found');
    if (order.deliveryMethod !== 'delivery')
      throw new BadRequestException('This order is not for home delivery.');
    if (order.status === 'CANCELLED')
      throw new BadRequestException('This order is cancelled.');

    const existing = order.delivery;
    if (existing?.externalId && !REBOOKABLE.includes(existing.status)) {
      return existing; // already booked and in flight
    }

    const cfg = await this.getConfig(businessId);
    if (!cfg)
      throw new BadRequestException(
        'Road Runner is not configured. Add ROADRUNNER_KEY_ID and ROADRUNNER_SECRET.',
      );

    let address = existing?.dropoffAddress || order.deliveryAddress || '';
    const lat = existing?.dropoffLat ?? order.deliveryLat;
    const lng = existing?.dropoffLng ?? order.deliveryLng;
    if (
      (!address || address.startsWith('Shared Location')) &&
      lat != null &&
      lng != null
    ) {
      address = (await this.geocoder.reverse(lat, lng)) || address;
    }
    if (!address)
      throw new BadRequestException('The order has no delivery address.');

    const delivery =
      existing ||
      (await this.createDraft(businessId, order.id, {
        address,
        lat,
        lng,
        currency: order.currency,
      }));

    const paid = order.paymentStatus === 'PAID';
    const instructions =
      lat != null && lng != null
        ? `Map pin: https://maps.google.com/?q=${lat},${lng}`
        : null;
    const reuseQuote = delivery.quoteId && !existing?.externalId; // a fresh quote is only good for the first booking

    const body: Record<string, unknown> = {
      client_reference: order.orderNumber,
      ...(reuseQuote ? { quote_id: delivery.quoteId } : {}),
      ...this.pickupFields(
        cfg,
        order.business.name,
        order.business.contactPhone,
      ),
      dropoff: {
        name: order.customerName || 'Customer',
        phone: this.toE164(order.customerPhone),
        address: address.slice(0, 512),
        country: 'Zimbabwe',
        instructions,
      },
      items: order.items.map((i) => ({
        name: i.productName.slice(0, 255),
        quantity: i.quantity,
        unit_price: Math.round(i.unitPrice * 100),
      })),
      delivery_fee: delivery.feeAmount ?? null,
      currency: order.currency,
      payment_type: paid ? 'prepaid' : 'cash_on_delivery',
      ...(paid
        ? {}
        : {
            cash_to_collect: Math.max(1, Math.round(order.totalAmount * 100)),
          }),
    };

    let rr: RoadrunnerDelivery;
    try {
      rr = await this.createWithIdempotency(cfg, order.orderNumber, body);
    } catch (err: any) {
      // An expired/used quote shouldn't block the booking — retry priced at booking time.
      if (
        body.quote_id &&
        err instanceof RoadrunnerError &&
        [409, 422].includes(err.status) &&
        /quote/i.test(`${err.code} ${err.message}`)
      ) {
        delete body.quote_id;
        try {
          rr = await this.createWithIdempotency(cfg, order.orderNumber, body);
        } catch (retryErr: any) {
          return this.markBookingFailed(delivery.id, retryErr);
        }
      } else {
        return this.markBookingFailed(delivery.id, err);
      }
    }

    const updated = await this.prisma.delivery.update({
      where: { id: delivery.id },
      data: {
        externalId: rr.id,
        status: rr.status || 'pending',
        trackingUrl: rr.tracking_url,
        dropoffAddress: address,
        feeAmount: rr.pricing?.delivery_fee?.amount ?? delivery.feeAmount,
        currency: rr.pricing?.delivery_fee?.currency || delivery.currency,
        lastError: null,
        bookedAt: new Date(),
        providerUpdatedAt: rr.updated_at ? new Date(rr.updated_at) : new Date(),
        // fresh booking: clear state left over from a cancelled/failed attempt
        courierName: null,
        courierPhone: null,
        eta: null,
        cancelledAt: null,
      },
    });
    await this.recordEvent(updated.id, {
      type: 'delivery.created',
      status: updated.status,
      source: 'api',
    });
    this.emitUpdate(businessId, order.id, order.orderNumber, updated.status);

    await this.notifyCustomer(
      businessId,
      order.customerPhone,
      `🚚 *Delivery booked — Order #${order.orderNumber}*\n\nYour order is booked with our courier and will be dispatched soon.` +
        (rr.tracking_url
          ? `\n\n📍 Track your delivery:\n${rr.tracking_url}`
          : ''),
    );
    return updated;
  }

  async refresh(businessId: string, orderId: string) {
    const { delivery, cfg } = await this.loadBooked(businessId, orderId);
    const rr = await this.client.getDelivery(cfg, delivery.externalId!);
    await this.applyRemoteState(delivery, rr, 'poll');
    await this.syncEvents(delivery, cfg).catch(() => undefined);
    return this.prisma.delivery.findUnique({ where: { id: delivery.id } });
  }

  async cancel(
    businessId: string,
    orderId: string,
    reason: string,
    note?: string,
  ) {
    const { delivery, cfg } = await this.loadBooked(businessId, orderId);
    if (TERMINAL.includes(delivery.status))
      throw new BadRequestException(`Delivery is already ${delivery.status}.`);
    try {
      const rr = await this.client.cancelDelivery(
        cfg,
        delivery.externalId!,
        reason,
        note,
      );
      await this.applyRemoteState(delivery, rr, 'api');
    } catch (err: any) {
      if (err instanceof RoadrunnerError && err.status === 403) {
        throw new BadRequestException(
          'Your Road Runner key is missing the deliveries:cancel scope. Ask Road Runner to enable it.',
        );
      }
      throw new BadRequestException(err.message);
    }
    return this.prisma.delivery.findUnique({ where: { id: delivery.id } });
  }

  async getTimeline(businessId: string, orderId: string) {
    const delivery = await this.prisma.delivery.findFirst({
      where: { orderId, businessId },
    });
    if (!delivery) return [];
    if (delivery.externalId) {
      const cfg = await this.getConfig(businessId);
      if (cfg)
        await this.syncEvents(delivery, cfg).catch((e) =>
          this.logger.warn(`Event sync failed: ${e.message}`),
        );
    }
    return this.prisma.deliveryEvent.findMany({
      where: { deliveryId: delivery.id },
      orderBy: { occurredAt: 'asc' },
    });
  }

  /** Every home-delivery order with its courier delivery (if any), newest first. */
  async listForBusiness(businessId: string) {
    return this.prisma.order.findMany({
      where: { businessId, deliveryMethod: 'delivery' },
      select: {
        id: true,
        orderNumber: true,
        status: true,
        paymentStatus: true,
        totalAmount: true,
        deliveryFee: true,
        currency: true,
        customerName: true,
        customerPhone: true,
        deliveryAddress: true,
        deliveryLat: true,
        deliveryLng: true,
        createdAt: true,
        items: {
          select: {
            id: true,
            productName: true,
            quantity: true,
            lineTotal: true,
          },
        },
        delivery: true,
      },
      orderBy: { createdAt: 'desc' },
      take: 300,
    });
  }

  async getPublicTracking(orderId: string) {
    const order = await this.prisma.order.findUnique({
      where: { id: orderId },
      select: {
        orderNumber: true,
        customerName: true,
        deliveryMethod: true,
        deliveryAddress: true,
        status: true,
        createdAt: true,
        business: { select: { name: true } },
        delivery: {
          select: {
            status: true,
            trackingUrl: true,
            courierName: true,
            eta: true,
            dropoffAddress: true,
            bookedAt: true,
            deliveredAt: true,
            updatedAt: true,
            events: {
              select: { type: true, status: true, occurredAt: true },
              orderBy: { occurredAt: 'asc' },
            },
          },
        },
      },
    });
    if (!order) throw new NotFoundException('Order not found');
    return order;
  }

  // ── Webhooks ───────────────────────────────────────────────────────────────

  /** Returns false when the signature doesn't verify. Processing happens after the 2xx is sent. */
  async handleWebhook(
    rawBody: Buffer,
    headers: Record<string, any>,
  ): Promise<boolean> {
    const eventType = String(headers['x-rr-event'] || '');
    const eventId = String(headers['x-rr-event-id'] || '');
    const timestamp = String(headers['x-rr-timestamp'] || '');
    const signature = String(headers['x-rr-signature'] || '');

    let payload: any;
    try {
      payload = JSON.parse(rawBody.toString('utf8'));
    } catch {
      return false;
    }
    const resource: RoadrunnerDelivery | undefined =
      payload?.data?.object || payload?.data || undefined;
    const externalId = resource?.id;

    const delivery = externalId
      ? await this.prisma.delivery.findUnique({ where: { externalId } })
      : null;
    const cfg = delivery ? await this.getConfig(delivery.businessId) : null;
    const secret = cfg?.webhookSecret || process.env.ROADRUNNER_WEBHOOK_SECRET;

    if (
      !secret ||
      !this.client.verifyWebhook(secret, timestamp, signature, rawBody)
    ) {
      this.logger.warn(
        `Rejected Road Runner webhook ${eventId} (${eventType}): bad signature`,
      );
      return false;
    }

    setImmediate(() => {
      this.processWebhook(
        delivery,
        resource,
        eventType || payload?.type,
        eventId || payload?.id,
      ).catch((err) =>
        this.logger.error(
          `Road Runner webhook ${eventId} processing failed: ${err.message}`,
        ),
      );
    });
    return true;
  }

  private async processWebhook(
    delivery: Delivery | null,
    resource: RoadrunnerDelivery | undefined,
    type: string,
    eventId: string,
  ) {
    if (!delivery || !resource) {
      this.logger.log(
        `Road Runner webhook ${eventId} (${type}) for unknown delivery ${resource?.id || '-'} — ignored`,
      );
      return;
    }
    if (
      eventId &&
      (await this.prisma.deliveryEvent.findUnique({
        where: { externalEventId: eventId },
      }))
    ) {
      return; // at-least-once delivery: already handled
    }
    await this.recordEvent(delivery.id, {
      externalEventId: eventId || undefined,
      type: type || `delivery.${resource.status}`,
      status: resource.status,
      source: 'webhook',
      occurredAt: resource.updated_at
        ? new Date(resource.updated_at)
        : new Date(),
    });
    await this.applyRemoteState(delivery, resource, 'webhook');
  }

  // ── Internals ──────────────────────────────────────────────────────────────

  private async applyRemoteState(
    delivery: Delivery,
    rr: RoadrunnerDelivery,
    source: string,
  ) {
    const remoteUpdated = rr.updated_at ? new Date(rr.updated_at) : new Date();
    if (
      delivery.providerUpdatedAt &&
      remoteUpdated < delivery.providerUpdatedAt
    ) {
      return; // out-of-order event: we already hold something newer
    }

    const updated = await this.prisma.delivery.update({
      where: { id: delivery.id },
      data: {
        status: rr.status,
        trackingUrl: rr.tracking_url || delivery.trackingUrl,
        courierName: rr.courier?.name ?? delivery.courierName,
        courierPhone: rr.courier?.phone ?? delivery.courierPhone,
        eta: rr.eta,
        feeAmount: rr.pricing?.delivery_fee?.amount ?? delivery.feeAmount,
        lastError:
          rr.hold?.message ||
          (rr.status === 'dispatch_failed'
            ? 'Courier network could not dispatch this delivery'
            : null),
        providerUpdatedAt: remoteUpdated,
        deliveredAt: rr.delivered_at
          ? new Date(rr.delivered_at)
          : delivery.deliveredAt,
        cancelledAt: rr.cancelled_at
          ? new Date(rr.cancelled_at)
          : delivery.cancelledAt,
      },
      include: {
        order: { select: { id: true, orderNumber: true, customerPhone: true } },
      },
    });

    if (updated.status === delivery.status) return;
    this.logger.log(
      `Delivery ${updated.externalId} ${delivery.status} → ${updated.status} (${source})`,
    );

    if (updated.status === 'delivered') {
      await this.prisma.order.update({
        where: { id: updated.orderId },
        data: { status: 'COMPLETED', fulfilmentStatus: 'FULFILLED' },
      });
    }
    this.emitUpdate(
      updated.businessId,
      updated.orderId,
      updated.order.orderNumber,
      updated.status,
    );

    const message = CUSTOMER_MESSAGES[updated.status]?.(
      updated,
      updated.order.orderNumber,
    );
    if (message)
      await this.notifyCustomer(
        updated.businessId,
        updated.order.customerPhone,
        message,
      );
  }

  private async syncEvents(delivery: Delivery, cfg: RoadrunnerConfig) {
    const { data } = await this.client.getEvents(cfg, delivery.externalId!);
    for (const e of data || []) {
      await this.recordEvent(delivery.id, {
        externalEventId: e.id,
        type: e.type,
        status: e.status,
        source: e.source,
        occurredAt: new Date(e.occurred_at),
        data: e.data,
      });
    }
  }

  private async recordEvent(
    deliveryId: string,
    e: {
      externalEventId?: string;
      type: string;
      status?: string;
      source?: string;
      occurredAt?: Date;
      data?: unknown;
    },
  ) {
    const row = {
      deliveryId,
      type: e.type,
      status: e.status,
      source: e.source,
      occurredAt: e.occurredAt || new Date(),
      dataJson: e.data ? JSON.stringify(e.data) : null,
    };
    if (!e.externalEventId)
      return this.prisma.deliveryEvent.create({ data: row });
    return this.prisma.deliveryEvent.upsert({
      where: { externalEventId: e.externalEventId },
      create: { ...row, externalEventId: e.externalEventId },
      update: {},
    });
  }

  private async loadBooked(businessId: string, orderId: string) {
    const delivery = await this.prisma.delivery.findFirst({
      where: { orderId, businessId },
    });
    if (!delivery?.externalId)
      throw new BadRequestException(
        'This order has not been booked with the courier yet.',
      );
    const cfg = await this.getConfig(businessId);
    if (!cfg) throw new BadRequestException('Road Runner is not configured.');
    return { delivery, cfg };
  }

  /** The Idempotency-Key is tied to the body, so a retry of the same request is safe and a changed request gets a new key. */
  private createWithIdempotency(
    cfg: RoadrunnerConfig,
    orderNumber: string,
    body: Record<string, unknown>,
  ) {
    const hash = crypto
      .createHash('sha256')
      .update(JSON.stringify(body))
      .digest('hex')
      .slice(0, 12);
    return this.client.createDelivery(cfg, body, `${orderNumber}-${hash}`);
  }

  private async markBookingFailed(
    deliveryId: string,
    err: any,
  ): Promise<never> {
    await this.prisma.delivery.update({
      where: { id: deliveryId },
      data: {
        status: 'booking_failed',
        lastError: String(err.message).slice(0, 1000),
      },
    });
    throw new BadRequestException(`Road Runner booking failed: ${err.message}`);
  }

  private pickupFields(
    cfg: RoadrunnerConfig,
    name?: string,
    phone?: string | null,
  ) {
    if (cfg.pickupLocationId) return { pickup_location: cfg.pickupLocationId };
    if (!cfg.pickupAddress) return {}; // Road Runner falls back to the account's default pickup
    return {
      pickup: {
        address: cfg.pickupAddress,
        ...(name ? { name } : {}),
        ...(phone ? { phone: this.toE164(phone) } : {}),
      },
    };
  }

  private toE164(phone?: string | null): string | undefined {
    const digits = normalizePhoneNumber(phone);
    return digits ? `+${digits}` : undefined;
  }

  private emitUpdate(
    businessId: string,
    orderId: string,
    orderNumber: string,
    status: string,
  ) {
    try {
      this.moduleRef
        .get(OrderEventsService, { strict: false })
        .emitOrderUpdate(businessId, {
          type: 'order_updated',
          orderId,
          orderNumber,
          status,
        });
    } catch {
      // SSE is best-effort
    }
  }

  private async notifyCustomer(
    businessId: string,
    phone: string,
    message: string,
  ) {
    try {
      await this.moduleRef
        .get(PaymentPollingService, { strict: false })
        .notify(businessId, phone, message);
    } catch (err: any) {
      this.logger.warn(`Could not notify customer ${phone}: ${err.message}`);
    }
  }
}
