import { Injectable, Logger } from '@nestjs/common';
import axios, { Method } from 'axios';
import * as crypto from 'crypto';

export interface RoadrunnerConfig {
  baseUrl: string; // e.g. https://staging.roadrunnerzw.com/api
  keyId: string;
  secret: string;
  webhookSecret?: string;
  pickupAddress?: string;
  pickupLocationId?: string; // pl_… saved in the Road Runner portal
  depotLat?: number;
  depotLng?: number;
  maxRadiusKm?: number;
}

export interface RoadrunnerMoney {
  amount: number;
  currency: string;
}

export interface RoadrunnerQuote {
  id: string;
  serviceable: boolean;
  pricing_mode: string;
  distance_metres: number | null;
  delivery_fee: RoadrunnerMoney;
  fee_reason: string;
  expires_at: string;
}

export interface RoadrunnerDelivery {
  id: string;
  client_reference: string;
  status: string;
  test_mode: boolean;
  tracking_url: string;
  courier: { name: string | null; phone: string | null } | null;
  eta: string | null;
  pricing: {
    subtotal: RoadrunnerMoney | null;
    delivery_fee: RoadrunnerMoney | null;
    tax: RoadrunnerMoney | null;
    total: RoadrunnerMoney | null;
  };
  hold: {
    reasons: string[];
    message: string | null;
    since: string | null;
  } | null;
  created_at: string | null;
  updated_at: string | null;
  dispatched_at: string | null;
  delivered_at: string | null;
  cancelled_at: string | null;
  cancellation_reason: string | null;
}

export interface RoadrunnerEvent {
  id: string;
  type: string;
  status: string;
  occurred_at: string;
  source: string;
  data: Record<string, unknown> | null;
}

export class RoadrunnerError extends Error {
  constructor(
    public readonly status: number,
    public readonly type: string,
    public readonly code: string,
    message: string,
    public readonly requestId?: string,
  ) {
    super(message);
  }
}

/**
 * Thin signed HTTP client for the Road Runner API.
 * Every request is HMAC-signed: key_id.timestamp.METHOD.host+path.sha256(body)
 */
@Injectable()
export class RoadrunnerClient {
  private readonly logger = new Logger(RoadrunnerClient.name);

  ping(cfg: RoadrunnerConfig) {
    return this.request<{
      ok: boolean;
      client: string;
      scopes: string[] | string;
      test_mode: boolean | string;
      server_time: string;
    }>(cfg, 'GET', '/v1/ping');
  }

  createQuote(cfg: RoadrunnerConfig, body: Record<string, unknown>) {
    return this.request<RoadrunnerQuote>(cfg, 'POST', '/v1/quotes', body);
  }

  createDelivery(
    cfg: RoadrunnerConfig,
    body: Record<string, unknown>,
    idempotencyKey: string,
  ) {
    return this.request<RoadrunnerDelivery>(
      cfg,
      'POST',
      '/v1/deliveries',
      body,
      {
        'Idempotency-Key': idempotencyKey,
      },
    );
  }

  getDelivery(cfg: RoadrunnerConfig, id: string) {
    return this.request<RoadrunnerDelivery>(
      cfg,
      'GET',
      `/v1/deliveries/${encodeURIComponent(id)}`,
    );
  }

  getEvents(cfg: RoadrunnerConfig, id: string) {
    return this.request<{ data: RoadrunnerEvent[]; has_more: boolean }>(
      cfg,
      'GET',
      `/v1/deliveries/${encodeURIComponent(id)}/events`,
    );
  }

  cancelDelivery(
    cfg: RoadrunnerConfig,
    id: string,
    reason: string,
    note?: string,
  ) {
    return this.request<RoadrunnerDelivery>(
      cfg,
      'POST',
      `/v1/deliveries/${encodeURIComponent(id)}/cancel`,
      {
        reason,
        note: note || null,
      },
    );
  }

  listPickupLocations(cfg: RoadrunnerConfig) {
    return this.request<{ data: any }>(cfg, 'GET', '/v1/pickup-locations');
  }

  /** Verify an inbound webhook. The header may carry several comma-separated signatures during secret rotation. */
  verifyWebhook(
    secret: string,
    timestamp: string,
    signatureHeader: string,
    rawBody: Buffer | string,
  ): boolean {
    const ts = parseInt(timestamp, 10);
    if (!ts || Math.abs(Date.now() / 1000 - ts) > 300) return false;

    const expected = crypto
      .createHmac('sha256', secret)
      .update(`${timestamp}.${sha256Hex(rawBody)}`)
      .digest('hex');
    const expectedBuf = Buffer.from(expected);

    let ok = false;
    for (const candidate of signatureHeader.split(',')) {
      const buf = Buffer.from(candidate.trim());
      if (
        buf.length === expectedBuf.length &&
        crypto.timingSafeEqual(buf, expectedBuf)
      )
        ok = true;
    }
    return ok;
  }

  private async request<T>(
    cfg: RoadrunnerConfig,
    method: Method,
    path: string,
    body?: unknown,
    extraHeaders: Record<string, string> = {},
  ): Promise<T> {
    const url = new URL(cfg.baseUrl.replace(/\/+$/, '') + path);
    const raw = body === undefined ? '' : JSON.stringify(body);
    const timestamp = Math.floor(Date.now() / 1000).toString();
    const upper = method.toUpperCase();

    // host without port, path includes the /api prefix and query string
    const signingString = `${cfg.keyId}.${timestamp}.${upper}.${url.hostname}${url.pathname}${url.search}.${sha256Hex(raw)}`;
    const signature = crypto
      .createHmac('sha256', cfg.secret)
      .update(signingString)
      .digest('hex');

    const res = await axios.request({
      method: upper as Method,
      url: url.toString(),
      data: raw || undefined,
      transformRequest: [(d) => d], // send the exact bytes we signed
      headers: {
        Authorization: `Bearer ${cfg.keyId}`,
        'X-RR-Timestamp': timestamp,
        'X-RR-Signature': signature,
        Accept: 'application/json',
        ...(raw ? { 'Content-Type': 'application/json' } : {}),
        ...extraHeaders,
      },
      timeout: 15000,
      validateStatus: () => true,
    });

    if (res.status >= 200 && res.status < 300) {
      return res.data as T;
    }

    const err = res.data?.error || {};
    const detail =
      Array.isArray(err.details) && err.details.length
        ? ` (${err.details.map((d: any) => `${d.field}: ${d.issue}`).join(', ')})`
        : '';
    this.logger.warn(
      `Road Runner ${upper} ${path} → ${res.status} ${err.code || ''} ${err.message || ''}${detail} [${err.request_id || '-'}]`,
    );
    throw new RoadrunnerError(
      res.status,
      err.type || 'http_error',
      err.code || String(res.status),
      (err.message || `Road Runner request failed with status ${res.status}`) +
        detail,
      err.request_id,
    );
  }
}

function sha256Hex(data: Buffer | string): string {
  return crypto.createHash('sha256').update(data).digest('hex');
}
