import type { InsurancePurchaseRecord, InsuranceType } from '../types';
import { daysUntilExpire, isEmpty } from './vehicle';

export interface VehicleInsuranceExpire {
  compulsory?: string;
  commercial?: string;
}

export type InsuranceCoverageState = 'not_purchased' | 'expired' | 'valid';

export function getInsuranceCoverageState(expireDate?: string): InsuranceCoverageState {
  if (isEmpty(expireDate)) return 'not_purchased';
  const days = daysUntilExpire(expireDate!);
  if (days === null) return 'not_purchased';
  if (days < 0) return 'expired';
  return 'valid';
}

/** 保险状态悬浮提示：仅展示到期或未购买的险种 */
export function buildInsuranceStatusTooltip(insurance: VehicleInsuranceExpire): string | undefined {
  const hints: string[] = [];
  const compulsory = getInsuranceCoverageState(insurance.compulsory);
  const commercial = getInsuranceCoverageState(insurance.commercial);
  if (compulsory === 'not_purchased') hints.push('交强险未购买');
  else if (compulsory === 'expired') hints.push('交强险到期');
  if (commercial === 'not_purchased') hints.push('商业险未购买');
  else if (commercial === 'expired') hints.push('商业险到期');
  return hints.length ? hints.join('；') : undefined;
}

function isNewerPurchase(
  candidate: InsurancePurchaseRecord,
  current: InsurancePurchaseRecord,
): boolean {
  const candidateAt = candidate.purchasedAt || candidate.expireDate;
  const currentAt = current.purchasedAt || current.expireDate;
  if (candidateAt !== currentAt) return candidateAt > currentAt;
  return candidate.id > current.id;
}

/** 按车辆汇总保险采购中各险种最新一条的到期日 */
export function buildInsuranceExpireMap(
  purchases: InsurancePurchaseRecord[],
): Map<string, VehicleInsuranceExpire> {
  const latestByVehicle = new Map<string, Map<InsuranceType, InsurancePurchaseRecord>>();

  for (const purchase of purchases) {
    let byType = latestByVehicle.get(purchase.vehicleId);
    if (!byType) {
      byType = new Map();
      latestByVehicle.set(purchase.vehicleId, byType);
    }
    const existing = byType.get(purchase.insuranceType);
    if (!existing || isNewerPurchase(purchase, existing)) {
      byType.set(purchase.insuranceType, purchase);
    }
  }

  const result = new Map<string, VehicleInsuranceExpire>();
  for (const [vehicleId, byType] of latestByVehicle) {
    result.set(vehicleId, {
      compulsory: byType.get('交强险')?.expireDate,
      commercial: byType.get('商业险')?.expireDate,
    });
  }
  return result;
}

export function resolveVehicleInsuranceExpire(
  vehicleId: string,
  expireMap: Map<string, VehicleInsuranceExpire>,
): VehicleInsuranceExpire {
  return expireMap.get(vehicleId) ?? {};
}
