export type OrderState =
  | 'PENDING'
  | 'AWAITING_PAYMENT'
  | 'PAID'
  | 'PROCESSING'
  | 'SHIPPED'
  | 'DELIVERED'
  | 'CANCELLED'
  | 'REFUNDED'
  | 'PARTIALLY_REFUNDED';

export interface OrderItemInput {
  productId: string;
  variantId: string;
  sku: string;
  ean: string | null;
  name: string;
  unitPriceCents: number;
  discountCents: number;
  taxCents: number;
  quantity: number;
}

export interface OrderItem extends OrderItemInput {
  id: string;
  orderId: string;
  createdAt: Date;
}

export interface Order {
  id: string;
  userId: string;
  idempotencyKey: string | null;
  state: OrderState;
  currency: 'EUR';
  subtotalCents: number;
  discountCents: number;
  taxCents: number;
  totalCents: number;
  trackingNumber?: string | null;
  courier?: string | null;
  createdAt: Date;
  updatedAt: Date;
}

export interface OrderView extends Order {
  items: OrderItem[];
}

export const ALLOWED_TRANSITIONS: Readonly<Record<OrderState, ReadonlyArray<OrderState>>> = {
  PENDING: ['AWAITING_PAYMENT', 'CANCELLED'],
  AWAITING_PAYMENT: ['PAID', 'CANCELLED'],
  PAID: ['PROCESSING', 'SHIPPED', 'CANCELLED', 'REFUNDED'],
  PROCESSING: ['SHIPPED', 'CANCELLED', 'REFUNDED'],
  SHIPPED: ['DELIVERED', 'PARTIALLY_REFUNDED'],
  DELIVERED: ['PARTIALLY_REFUNDED'],
  CANCELLED: [],
  REFUNDED: [],
  PARTIALLY_REFUNDED: [],
};

export function isTransitionAllowed(from: OrderState, to: OrderState): boolean {
  return ALLOWED_TRANSITIONS[from].includes(to);
}
