import { createHmac, timingSafeEqual } from 'node:crypto';
import { env } from '../config/env';

/**
 * A thin Razorpay client over fetch: Payment Links, Route linked accounts,
 * and webhook signature checks. No SDK — the surface we use is small, and a
 * plain HTTP client is what lets the smoke suite point RAZORPAY_BASE_URL at
 * a fake server and exercise every path without a Razorpay account.
 *
 * Money is in paise on the wire and whole rupees everywhere else in the
 * product; the conversion happens in the callers, never here.
 */

export function isRazorpayConfigured(): boolean {
  return !!env.RAZORPAY_KEY_ID && !!env.RAZORPAY_KEY_SECRET;
}

export class RazorpayError extends Error {
  constructor(
    message: string,
    public readonly status: number,
    public readonly code?: string,
  ) {
    super(message);
    this.name = 'RazorpayError';
  }
}

async function call<T>(method: 'GET' | 'POST' | 'PATCH', path: string, body?: unknown): Promise<T> {
  if (!isRazorpayConfigured()) throw new RazorpayError('Razorpay is not configured on this server', 503, 'GATEWAY_NOT_CONFIGURED');
  const auth = Buffer.from(`${env.RAZORPAY_KEY_ID}:${env.RAZORPAY_KEY_SECRET}`).toString('base64');
  let res: Response;
  try {
    res = await fetch(`${env.RAZORPAY_BASE_URL}${path}`, {
      method,
      headers: { Authorization: `Basic ${auth}`, 'Content-Type': 'application/json', Accept: 'application/json' },
      body: body === undefined ? undefined : JSON.stringify(body),
      signal: AbortSignal.timeout(15_000),
    });
  } catch (err) {
    throw new RazorpayError(`Could not reach the payment gateway: ${(err as Error).message}`, 503, 'GATEWAY_UNREACHABLE');
  }
  const text = await res.text();
  let json: unknown = {};
  try {
    json = text ? JSON.parse(text) : {};
  } catch {
    json = { raw: text };
  }
  if (!res.ok) {
    const e = (json as { error?: { description?: string; code?: string } }).error;
    throw new RazorpayError(e?.description || `Payment gateway answered ${res.status}`, res.status, e?.code);
  }
  return json as T;
}

// ── Payment Links ──────────────────────────────────────────────────────────

export interface PaymentLinkInput {
  amountPaise: number;
  referenceId: string;
  description: string;
  customer: { name: string; email?: string | null; contact?: string | null };
  notes: Record<string, string>;
  callbackUrl: string;
  /** Unix seconds. Razorpay insists on at least 15 minutes ahead. */
  expireBy: number;
  /** Route: send this much to the hostel's linked account; the rest stays with the platform. */
  transfer?: { account: string; amountPaise: number; notes: Record<string, string> } | null;
}

export interface PaymentLink {
  id: string;
  short_url: string;
  status: string; // created | paid | expired | cancelled | partially_paid
  amount: number;
  reference_id?: string;
  expire_by?: number;
  notes?: Record<string, string>;
  /** Present on a fetch: the payments made against the link. */
  payments?: { payment_id: string; amount: number; status: string; method?: string; created_at: number }[];
}

export interface RzpPayment {
  id: string;
  amount: number;
  status: string; // created | authorized | captured | refunded | failed
  method?: string;
  order_id?: string | null;
  invoice_id?: string | null;
  created_at: number;
  notes?: Record<string, string> | string[];
  acquirer_data?: Record<string, string | null>;
  amount_refunded?: number;
}

/** Captured payments in a time window (unix seconds), newest first, paged. */
export async function listPayments(fromUnix: number, toUnix: number): Promise<RzpPayment[]> {
  const out: RzpPayment[] = [];
  for (let skip = 0; skip < 5000; skip += 100) {
    const page = await call<{ items: RzpPayment[]; count: number }>('GET', `/v1/payments?from=${fromUnix}&to=${toUnix}&count=100&skip=${skip}`);
    out.push(...(page.items ?? []));
    if (!page.items || page.items.length < 100) break;
  }
  return out;
}

export interface RzpRefund {
  id: string;
  payment_id: string;
  amount: number;
  status: string; // pending | processed | failed
  created_at?: number;
}

/** Refund a payment, reversing any Route transfer with it. */
export function createRefund(paymentId: string, amountPaise: number | undefined, notes: Record<string, string>): Promise<RzpRefund> {
  return call<RzpRefund>('POST', `/v1/payments/${paymentId}/refund`, {
    ...(amountPaise ? { amount: amountPaise } : {}),
    speed: 'normal',
    notes,
    reverse_all: 1,
  });
}

/** Route: move (part of) a captured payment to a linked account after the fact — used for virtual-account credits. */
export function transferPayment(paymentId: string, transfer: { account: string; amountPaise: number; notes: Record<string, string> }): Promise<{ items: { id: string; status?: string }[] }> {
  return call<{ items: { id: string; status?: string }[] }>('POST', `/v1/payments/${paymentId}/transfers`, {
    transfers: [{ account: transfer.account, amount: transfer.amountPaise, currency: 'INR', notes: transfer.notes, linked_account_notes: Object.keys(transfer.notes), on_hold: false }],
  });
}

// ── Smart Collect: virtual accounts ────────────────────────────────────────

export interface VirtualAccountEntity {
  id: string;
  status: string; // active | closed
  receivers: { entity: string; id: string; account_number?: string; ifsc?: string; bank_name?: string; name?: string; address?: string; username?: string; handle?: string }[];
}

export function createVirtualAccount(input: { description: string; notes: Record<string, string>; receiverName?: string }): Promise<VirtualAccountEntity> {
  return call<VirtualAccountEntity>('POST', '/v1/virtual_accounts', {
    receivers: { types: ['bank_account', 'vpa'] },
    description: input.description,
    notes: input.notes,
  });
}

export function fetchVirtualAccount(id: string): Promise<VirtualAccountEntity> {
  return call<VirtualAccountEntity>('GET', `/v1/virtual_accounts/${id}`);
}

export function closeVirtualAccount(id: string): Promise<VirtualAccountEntity> {
  return call<VirtualAccountEntity>('POST', `/v1/virtual_accounts/${id}/close`);
}

export function createPaymentLink(input: PaymentLinkInput): Promise<PaymentLink> {
  return call<PaymentLink>('POST', '/v1/payment_links', {
    amount: input.amountPaise,
    currency: 'INR',
    accept_partial: false,
    reference_id: input.referenceId,
    description: input.description,
    customer: {
      name: input.customer.name,
      ...(input.customer.email ? { email: input.customer.email } : {}),
      ...(input.customer.contact ? { contact: input.customer.contact } : {}),
    },
    // HostelCare delivers the link itself (in-app, reminder email, WhatsApp).
    notify: { sms: false, email: false },
    reminder_enable: false,
    notes: input.notes,
    callback_url: input.callbackUrl,
    callback_method: 'get',
    expire_by: input.expireBy,
    ...(input.transfer
      ? {
          options: {
            order: {
              transfers: [
                {
                  account: input.transfer.account,
                  amount: input.transfer.amountPaise,
                  currency: 'INR',
                  notes: input.transfer.notes,
                  linked_account_notes: Object.keys(input.transfer.notes),
                  on_hold: false,
                },
              ],
            },
          },
        }
      : {}),
  });
}

export function fetchPaymentLink(id: string): Promise<PaymentLink> {
  return call<PaymentLink>('GET', `/v1/payment_links/${id}`);
}

export function cancelPaymentLink(id: string): Promise<PaymentLink> {
  return call<PaymentLink>('POST', `/v1/payment_links/${id}/cancel`);
}

// ── Route: linked accounts ─────────────────────────────────────────────────

export interface LinkedAccount {
  id: string;
  status: string; // created | activated | needs_clarification | under_review | suspended
}
export interface RouteProduct {
  id: string;
  activation_status: string; // requested | needs_clarification | under_review | activated | rejected
}

export function createLinkedAccount(input: {
  email: string;
  phone: string;
  legalName: string;
  businessType: string;
  contactName: string;
  referenceId: string;
  address: { street1: string; city: string; state: string; postalCode: string };
  pan?: string;
}): Promise<LinkedAccount> {
  return call<LinkedAccount>('POST', '/v2/accounts', {
    email: input.email,
    phone: input.phone,
    type: 'route',
    reference_id: input.referenceId,
    legal_business_name: input.legalName,
    business_type: input.businessType,
    contact_name: input.contactName,
    profile: {
      category: env.RAZORPAY_BUSINESS_CATEGORY,
      subcategory: env.RAZORPAY_BUSINESS_SUBCATEGORY,
      addresses: {
        registered: {
          street1: input.address.street1,
          street2: '',
          city: input.address.city,
          state: input.address.state,
          postal_code: input.address.postalCode,
          country: 'IN',
        },
      },
    },
    ...(input.pan ? { legal_info: { pan: input.pan } } : {}),
  });
}

export function createStakeholder(accountId: string, input: { name: string; email: string; pan: string }): Promise<{ id: string }> {
  return call<{ id: string }>('POST', `/v2/accounts/${accountId}/stakeholders`, {
    name: input.name,
    email: input.email,
    kyc: { pan: input.pan },
  });
}

export function requestRouteProduct(accountId: string): Promise<RouteProduct> {
  return call<RouteProduct>('POST', `/v2/accounts/${accountId}/products`, { product_name: 'route', tnc_accepted: true });
}

export function setRouteSettlement(accountId: string, productId: string, bank: { accountNumber: string; ifsc: string; beneficiaryName: string }): Promise<RouteProduct> {
  return call<RouteProduct>('PATCH', `/v2/accounts/${accountId}/products/${productId}`, {
    settlements: { account_number: bank.accountNumber, ifsc_code: bank.ifsc, beneficiary_name: bank.beneficiaryName },
    tnc_accepted: true,
  });
}

export function fetchLinkedAccount(accountId: string): Promise<LinkedAccount> {
  return call<LinkedAccount>('GET', `/v2/accounts/${accountId}`);
}

export function fetchRouteProduct(accountId: string, productId: string): Promise<RouteProduct> {
  return call<RouteProduct>('GET', `/v2/accounts/${accountId}/products/${productId}`);
}

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

/** HMAC-SHA256 of the raw body with the webhook secret, compared in constant time. */
export function verifyWebhookSignature(rawBody: Buffer | string, signature: string | undefined): boolean {
  const secret = env.RAZORPAY_WEBHOOK_SECRET;
  if (!secret || !signature || !rawBody) return false;
  const digest = createHmac('sha256', secret).update(rawBody).digest('hex');
  const a = Buffer.from(digest, 'utf8');
  const b = Buffer.from(signature, 'utf8');
  return a.length === b.length && timingSafeEqual(a, b);
}

export function isWebhookConfigured(): boolean {
  return !!env.RAZORPAY_WEBHOOK_SECRET;
}
