import type { LeaseBusinessDetailRow } from '../types';
import seedRecords from '../data/hydrogen-refuel-records.json';

export interface HydrogenRefuelRecord {
  hydrogenTime: string;
  stationName: string;
  customerName: string;
  plateNo: string;
  hydrogenKg: number;
  unitPrice: number;
  totalPrice: number;
  borneBy: '我司承担' | '客户承担';
}

const HYDROGEN_REFUEL_RECORDS = seedRecords as HydrogenRefuelRecord[];

function roundMoney(value: number): number {
  return Math.round(value * 100) / 100;
}

function parseDateOnly(value: string): Date | null {
  if (!value) return null;
  const datePart = value.trim().slice(0, 10);
  const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(datePart);
  if (!match) return null;
  const year = Number(match[1]);
  const month = Number(match[2]);
  const day = Number(match[3]);
  return new Date(year, month - 1, day);
}

function lastDayOfMonth(year: number, month: number): Date {
  return new Date(year, month, 0);
}

function firstDayOfMonth(year: number, month: number): Date {
  return new Date(year, month - 1, 1);
}

/** 提车～退车与账单月份的交集，作为加氢记录筛选区间 */
function resolveHydrogenDateRange(
  row: Pick<LeaseBusinessDetailRow, 'year' | 'month' | 'pickupDate' | 'returnDate'>,
): { start: Date; end: Date } | null {
  const pickup = parseDateOnly(row.pickupDate ?? '');
  if (!pickup) return null;

  const monthStart = firstDayOfMonth(row.year, row.month);
  const monthEnd = lastDayOfMonth(row.year, row.month);
  const returnDate = parseDateOnly(row.returnDate ?? '');
  const leaseEnd = returnDate ?? monthEnd;

  const start = pickup > monthStart ? pickup : monthStart;
  const end = leaseEnd < monthEnd ? leaseEnd : monthEnd;
  if (start > end) return null;
  return { start, end };
}

function recordDate(record: HydrogenRefuelRecord): Date | null {
  return parseDateOnly(record.hydrogenTime);
}

function normalizeCustomer(value: string): string {
  return (value ?? '').trim();
}

export function getHydrogenRefuelRecords(
  row: Pick<
    LeaseBusinessDetailRow,
    'plateNo' | 'customerName' | 'year' | 'month' | 'pickupDate' | 'returnDate'
  >,
  records: HydrogenRefuelRecord[] = HYDROGEN_REFUEL_RECORDS,
): HydrogenRefuelRecord[] {
  const range = resolveHydrogenDateRange(row);
  if (!range) return [];

  const customer = normalizeCustomer(row.customerName);
  return records.filter((item) => {
    if (item.plateNo !== row.plateNo) return false;
    if (normalizeCustomer(item.customerName) !== customer) return false;
    if (item.borneBy !== '我司承担') return false;
    const date = recordDate(item);
    if (!date) return false;
    return date >= range.start && date <= range.end;
  });
}

export function sumHydrogenFeeForDetailRow(
  row: Pick<
    LeaseBusinessDetailRow,
    'plateNo' | 'customerName' | 'year' | 'month' | 'pickupDate' | 'returnDate'
  >,
  records?: HydrogenRefuelRecord[],
): number {
  return roundMoney(
    getHydrogenRefuelRecords(row, records)
      .reduce((sum, item) => sum + item.totalPrice, 0),
  );
}

export { HYDROGEN_REFUEL_RECORDS };
