export type OrderState =
  | 'PENDING'
  | 'AWAITING_PAYMENT'
  | 'PAID'
  | 'PROCESSING'
  | 'SHIPPED'
  | 'DELIVERED'
  | 'COMPLETED'
  | '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 Address {
  recipientName: string;
  street: string;
  city: string;
  postalCode: string;
  country: string;
}

export interface PaymentInfo {
  provider: string;
  status: string;
  amountCents: number;
  last4: string | null;
  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;
  customerName?: string | null;
  customerPhone?: string | null;
  createdAt: Date;
  updatedAt: Date;
}

export interface OrderView extends Order {
  items: OrderItem[];
  email?: string | null;
  phone?: string | null;
  shippingAddress?: Address | null;
  billingAddress?: Address | null;
  payment?: PaymentInfo | null;
}

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

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