import { ChangeDetectionStrategy, Component, computed, input } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AdminOrder } from '../../models/admin-order.model';

/**
 * Reconstructs "why was this amount charged" per
 * PHASE-1-MONEY-FX-PAYMENTS-CONTRACT.md §5.3:
 *   total = sum(line.unitPrice * qty) - discounts + delivery + fees
 * with the FX quote used, if any.
 *
 * Pure presentational: renders exactly what AdminOrder carries and nothing
 * it doesn't. Most orders today have none of the optional pricing fields -
 * this must read as "not available for this order", never guess a number
 * the backend never sent.
 */
@Component({
  selector: 'app-order-total-formula',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './order-total-formula.component.html',
  styleUrl: './order-total-formula.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class OrderTotalFormulaComponent {
  readonly order = input.required<AdminOrder>();

  /** True only when every line carries a reconstructable unit price. */
  readonly hasFullBreakdown = computed(() => {
    const items = this.order().items;
    return items.length > 0 && items.every(item => item.unitPriceMinor !== undefined);
  });

  readonly lineRows = computed(() =>
    this.order().items.map(item => ({
      name: item.name,
      quantity: item.quantity,
      unitPriceMinor: item.unitPriceMinor,
      lineTotalMinor: item.lineTotalMinor,
      discountMinor: item.discountMinor,
    })),
  );

  readonly subtotalMinor = computed(() => {
    if (!this.hasFullBreakdown()) {
      return null;
    }
    return this.lineRows().reduce((sum, row) => sum + (row.lineTotalMinor ?? 0), 0);
  });

  readonly totalDiscountMinor = computed(() =>
    this.lineRows().reduce((sum, row) => sum + (row.discountMinor ?? 0), 0),
  );

  toDisplay(minor: number | null | undefined): string | null {
    if (minor === null || minor === undefined) {
      return null;
    }
    return (minor / 100).toFixed(2);
  }
}
