import { PaymentAccountStatus, type HostelPaymentAccount } from '@prisma/client';
import { db, prismaUnscoped } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { env } from '../../config/env';
import { BadRequestError } from '../../lib/errors';
import * as rzp from '../../lib/razorpay';

/**
 * The hostel's bank account as a Razorpay Route linked account.
 *
 * One platform Razorpay account collects; Route pays each hostel into its
 * own bank. Setup walks Razorpay's steps in order and is idempotent per step,
 * so a failure half-way (a KYC rejection, a typo in the IFSC) is retried by
 * submitting again, not by starting over. Only the last four digits of the
 * account number are ever stored.
 */

export interface PaymentAccountInput {
  legalName: string;
  businessType: string;
  contactName: string;
  email: string;
  phone: string;
  addressLine: string;
  city: string;
  state: string;
  postalCode: string;
  beneficiaryName: string;
  /** Required until the Route product has settlement details; never stored. */
  accountNumber?: string;
  ifsc: string;
  /** Required by Razorpay for the account's stakeholder; stored masked. */
  pan?: string;
}

const ACCOUNT_STATUS: Record<string, PaymentAccountStatus> = {
  created: PaymentAccountStatus.CREATED,
  activated: PaymentAccountStatus.ACTIVE,
  needs_clarification: PaymentAccountStatus.NEEDS_CLARIFICATION,
  under_review: PaymentAccountStatus.UNDER_REVIEW,
  suspended: PaymentAccountStatus.REJECTED,
  rejected: PaymentAccountStatus.REJECTED,
};
const PRODUCT_STATUS: Record<string, PaymentAccountStatus> = {
  requested: PaymentAccountStatus.UNDER_REVIEW,
  needs_clarification: PaymentAccountStatus.NEEDS_CLARIFICATION,
  under_review: PaymentAccountStatus.UNDER_REVIEW,
  activated: PaymentAccountStatus.ACTIVE,
  rejected: PaymentAccountStatus.REJECTED,
};
export const mapAccountStatus = (s: string | undefined) => ACCOUNT_STATUS[s ?? ''] ?? PaymentAccountStatus.CREATED;
export const mapProductStatus = (s: string | undefined) => PRODUCT_STATUS[s ?? ''] ?? PaymentAccountStatus.UNDER_REVIEW;

const maskPan = (pan: string) => `${pan.slice(0, 2)}******${pan.slice(-2)}`;

export function publicAccount(a: HostelPaymentAccount | null) {
  if (!a) return null;
  const { razorpayStakeholderId: _s, ...rest } = a;
  return {
    ...rest,
    /** True when links can be created against this account. */
    ready: !!a.razorpayAccountId && a.productStatus === PaymentAccountStatus.ACTIVE,
    /** What still needs the owner: a rejection, a clarification, or Razorpay's review. */
    needsAction: a.accountStatus === PaymentAccountStatus.NEEDS_CLARIFICATION || a.productStatus === PaymentAccountStatus.NEEDS_CLARIFICATION || a.accountStatus === PaymentAccountStatus.REJECTED || a.productStatus === PaymentAccountStatus.REJECTED,
  };
}

/** What Settings → Payments shows: the gateway's availability, and the account if any. */
export async function getPaymentSetup() {
  const [account, settings] = await Promise.all([db.hostelPaymentAccount.findFirst({}), db.tenantSettings.findFirst({ select: { onlineCollectionEnabled: true, feeBearer: true, virtualAccountsEnabled: true } })]);
  return {
    gateway: { configured: rzp.isRazorpayConfigured(), routeRequired: env.RAZORPAY_ROUTE_REQUIRED },
    fees: {
      gatewayPercent: env.RAZORPAY_GATEWAY_FEE_PERCENT,
      gatewayTaxPercent: env.RAZORPAY_GATEWAY_FEE_TAX_PERCENT,
      routePercent: env.RAZORPAY_ROUTE_FEE_PERCENT,
      routeTaxPercent: env.RAZORPAY_ROUTE_FEE_TAX_PERCENT,
    },
    account: publicAccount(account),
    onlineCollectionEnabled: settings?.onlineCollectionEnabled ?? false,
    feeBearer: settings?.feeBearer ?? 'STUDENT',
    virtualAccountsEnabled: settings?.virtualAccountsEnabled ?? false,
  };
}

/**
 * Create or continue the hostel's linked account. Each Razorpay step runs
 * only if its id is missing, and the first failure is saved on the row so
 * the owner sees why rather than a generic error.
 */
export async function setupPaymentAccount(input: PaymentAccountInput) {
  const tenantId = getTenantIdOrThrow();
  if (!rzp.isRazorpayConfigured()) throw new BadRequestError('Online payments are not configured on this server yet', 'GATEWAY_NOT_CONFIGURED');

  const details = {
    legalName: input.legalName.trim(),
    businessType: input.businessType,
    contactName: input.contactName.trim(),
    email: input.email.trim().toLowerCase(),
    phone: input.phone.replace(/\s+/g, ''),
    addressLine: input.addressLine.trim(),
    city: input.city.trim(),
    state: input.state.trim(),
    postalCode: input.postalCode.trim(),
    beneficiaryName: input.beneficiaryName.trim(),
    ifsc: input.ifsc.trim().toUpperCase(),
    ...(input.accountNumber ? { accountLast4: input.accountNumber.slice(-4) } : {}),
    ...(input.pan ? { panMasked: maskPan(input.pan.toUpperCase()) } : {}),
  };
  const existing = await db.hostelPaymentAccount.findFirst({});
  let row = existing
    ? await db.hostelPaymentAccount.update({ where: { id: existing.id }, data: { ...details, lastError: null } })
    : await db.hostelPaymentAccount.create({ data: { tenantId, accountLast4: input.accountNumber?.slice(-4) ?? '', ...details } });

  const save = (data: Partial<HostelPaymentAccount>) => db.hostelPaymentAccount.update({ where: { id: row.id }, data });
  try {
    if (!row.razorpayAccountId) {
      const acc = await rzp.createLinkedAccount({
        email: row.email,
        phone: row.phone,
        legalName: row.legalName,
        businessType: row.businessType,
        contactName: row.contactName,
        // Stable across environments, so a re-created account maps back to this hostel.
        referenceId: `hc-${tenantId}`,
        address: { street1: row.addressLine, city: row.city, state: row.state, postalCode: row.postalCode },
        pan: input.pan?.toUpperCase(),
      });
      row = await save({ razorpayAccountId: acc.id, accountStatus: mapAccountStatus(acc.status), lastSyncedAt: new Date() });
    }
    if (!row.razorpayStakeholderId) {
      if (!input.pan) throw new BadRequestError('The account holder’s PAN is needed to complete KYC with Razorpay', 'PAN_REQUIRED');
      const sh = await rzp.createStakeholder(row.razorpayAccountId!, { name: row.contactName, email: row.email, pan: input.pan.toUpperCase() });
      row = await save({ razorpayStakeholderId: sh.id });
    }
    if (!row.razorpayProductId) {
      const product = await rzp.requestRouteProduct(row.razorpayAccountId!);
      row = await save({ razorpayProductId: product.id, productStatus: mapProductStatus(product.activation_status) });
    }
    if (row.productStatus !== PaymentAccountStatus.ACTIVE) {
      if (!input.accountNumber) throw new BadRequestError('Enter the bank account number to register it for settlements', 'ACCOUNT_NUMBER_REQUIRED');
      const product = await rzp.setRouteSettlement(row.razorpayAccountId!, row.razorpayProductId!, {
        accountNumber: input.accountNumber,
        ifsc: row.ifsc,
        beneficiaryName: row.beneficiaryName,
      });
      row = await save({ productStatus: mapProductStatus(product.activation_status), accountLast4: input.accountNumber.slice(-4), lastSyncedAt: new Date() });
    }
  } catch (err) {
    const message = err instanceof Error ? err.message : 'Setup failed';
    row = await save({ lastError: message });
    if (err instanceof BadRequestError) throw err;
    throw new BadRequestError(`Razorpay could not complete the setup: ${message}`, 'GATEWAY_SETUP_FAILED');
  }
  return publicAccount(row);
}

/** Ask Razorpay for the account's and product's current status — the fallback when a webhook was missed. */
export async function refreshPaymentAccount() {
  const row = await db.hostelPaymentAccount.findFirst({});
  if (!row?.razorpayAccountId) return publicAccount(row);
  const data: Partial<HostelPaymentAccount> = { lastSyncedAt: new Date() };
  const acc = await rzp.fetchLinkedAccount(row.razorpayAccountId);
  data.accountStatus = mapAccountStatus(acc.status);
  if (row.razorpayProductId) {
    const product = await rzp.fetchRouteProduct(row.razorpayAccountId, row.razorpayProductId);
    data.productStatus = mapProductStatus(product.activation_status);
  }
  return publicAccount(await db.hostelPaymentAccount.update({ where: { id: row.id }, data }));
}

/** Webhook side: Razorpay told us an account or product changed state. */
export async function applyAccountEvent(accountId: string, kind: 'account' | 'product', status: string | undefined): Promise<boolean> {
  const bare = accountId.replace(/^acc_/, '');
  const row = await prismaUnscoped.hostelPaymentAccount.findFirst({ where: { OR: [{ razorpayAccountId: accountId }, { razorpayAccountId: `acc_${bare}` }, { razorpayAccountId: bare }] } });
  if (!row) return false;
  await prismaUnscoped.hostelPaymentAccount.update({
    where: { id: row.id },
    data: kind === 'account' ? { accountStatus: mapAccountStatus(status), lastSyncedAt: new Date() } : { productStatus: mapProductStatus(status), lastSyncedAt: new Date() },
  });
  return true;
}

/** Unscoped: can this tenant take online payments right now? */
export async function onlineCollectionFor(tenantId: string): Promise<{ enabled: boolean; account: HostelPaymentAccount | null; reason: string | null }> {
  if (!rzp.isRazorpayConfigured()) return { enabled: false, account: null, reason: 'GATEWAY_NOT_CONFIGURED' };
  const [settings, account] = await Promise.all([
    prismaUnscoped.tenantSettings.findUnique({ where: { tenantId }, select: { onlineCollectionEnabled: true } }),
    prismaUnscoped.hostelPaymentAccount.findUnique({ where: { tenantId } }),
  ]);
  if (!settings?.onlineCollectionEnabled) return { enabled: false, account, reason: 'ONLINE_COLLECTION_OFF' };
  if (env.RAZORPAY_ROUTE_REQUIRED && !(account?.razorpayAccountId && account.productStatus === PaymentAccountStatus.ACTIVE)) {
    return { enabled: false, account, reason: 'PAYMENT_ACCOUNT_NOT_ACTIVE' };
  }
  return { enabled: true, account, reason: null };
}
