import { Injectable } from '@angular/core';
import { CartItem } from '../services/cart.service';

export interface Order {
    id: number;
    items: CartItem[];
    total: number;
    createdAt: string;
  }

@Injectable({
  providedIn: 'root'
})
export class OrderService {

  private ORDER_KEY = 'orders';

  constructor() {}

  createOrder(items: CartItem[]): number {
    const orderId = Date.now();
    const order = {
      id: orderId,
      items: items,
      total: items.reduce((sum, item) => sum + item.price * item.quantity, 0),
      createdAt: new Date().toISOString()
    };

    let orders = JSON.parse(localStorage.getItem(this.ORDER_KEY) || '[]');
    orders.push(order);
    localStorage.setItem(this.ORDER_KEY, JSON.stringify(orders));

    return orderId;
  }

  getOrders(): any[] {
    return JSON.parse(localStorage.getItem(this.ORDER_KEY) || '[]');
  }

  deleteOrder(orderId: number): void {
    let orders: Order[] = JSON.parse(localStorage.getItem(this.ORDER_KEY) || '[]');
    orders = orders.filter(order => order.id !== orderId);
    localStorage.setItem(this.ORDER_KEY, JSON.stringify(orders));
  }
}