import fs from "fs";
import path from "path";

export interface OrderItem {
  id: string;
  name: string;
  weight: string;
  price: number;
  quantity: number;
  thumbnail: string;
}

export interface OrderCustomer {
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
  nif?: string;
}

export interface OrderAddress {
  address: string;
  city: string;
  province: string;
  postalCode: string;
  country: string;
  deliveryNotes?: string;
}

export interface Order {
  id: string;
  orderNumber: string;
  date: string;
  status: "Pendiente" | "Pagado" | "En preparación" | "Enviado" | "Entregado" | "Cancelado";
  paymentMethod: "Redsys (Tarjeta)" | "Bizum" | "PayPal" | "Apple Pay / Google Pay";
  paymentStatus: "Completado" | "Pendiente" | "Rechazado";
  customer: OrderCustomer;
  shippingAddress: OrderAddress;
  items: OrderItem[];
  subtotal: number;
  discount: number;
  couponCode?: string;
  shippingCost: number;
  total: number;
  isGift: boolean;
  giftMessage?: string;
}

const ORDERS_FILE_PATH = path.join(process.cwd(), "src/data/orders_db.json");

// Default sample orders if file does not exist yet
const INITIAL_ORDERS: Order[] = [
  {
    id: "ord_1001",
    orderNumber: "RA-2026-1001",
    date: new Date(Date.now() - 3600000 * 4).toISOString(),
    status: "En preparación",
    paymentMethod: "Bizum",
    paymentStatus: "Completado",
    customer: {
      firstName: "María",
      lastName: "García López",
      email: "maria.garcia@example.com",
      phone: "622114455",
      nif: "48555123A",
    },
    shippingAddress: {
      address: "Calle Mayor, 12, 3ºB",
      city: "Madrid",
      province: "Madrid",
      postalCode: "28013",
      country: "España",
      deliveryNotes: "Dejar en conserjería si no estoy.",
    },
    items: [
      {
        id: "1259",
        name: "Panettone Milanés 1100-1200gr",
        weight: "1100 - 1200g",
        price: 32.5,
        quantity: 2,
        thumbnail: "https://raulasencio.es/wp-content/uploads/2014/12/Panttone-Milanes-2023-247x300.jpg",
      },
      {
        id: "1255",
        name: "Panettone Rocher 1100-1200gr",
        weight: "1100 - 1200g",
        price: 32.5,
        quantity: 1,
        thumbnail: "https://raulasencio.es/wp-content/uploads/2020/05/Panttone-Rocher-2023-247x300.jpg",
      },
    ],
    subtotal: 97.5,
    discount: 9.75,
    couponCode: "BIENVENIDO10",
    shippingCost: 0,
    total: 87.75,
    isGift: false,
  },
  {
    id: "ord_1002",
    orderNumber: "RA-2026-1002",
    date: new Date(Date.now() - 3600000 * 18).toISOString(),
    status: "Pagado",
    paymentMethod: "Redsys (Tarjeta)",
    paymentStatus: "Completado",
    customer: {
      firstName: "Carlos",
      lastName: "Fernández Navarro",
      email: "carlos.fn@example.com",
      phone: "655998877",
    },
    shippingAddress: {
      address: "Avinguda Diagonal, 450",
      city: "Barcelona",
      province: "Barcelona",
      postalCode: "08006",
      country: "España",
    },
    items: [
      {
        id: "33091",
        name: "Panettone de mango y chocolate con leche",
        weight: "1100 - 1200g",
        price: 32.5,
        quantity: 1,
        thumbnail: "https://raulasencio.es/wp-content/uploads/2026/07/PANETTONE-DE-MANGO.jpg-247x300.jpeg",
      },
    ],
    subtotal: 32.5,
    discount: 0,
    shippingCost: 0,
    total: 32.5,
    isGift: true,
    giftMessage: "¡Feliz aniversario! Disfruta del auténtico panettone artesano.",
  },
];

export function getOrders(): Order[] {
  try {
    if (!fs.existsSync(ORDERS_FILE_PATH)) {
      fs.writeFileSync(ORDERS_FILE_PATH, JSON.stringify(INITIAL_ORDERS, null, 2), "utf-8");
      return INITIAL_ORDERS;
    }
    const data = fs.readFileSync(ORDERS_FILE_PATH, "utf-8");
    return JSON.parse(data);
  } catch (e) {
    console.error("Error reading orders file:", e);
    return INITIAL_ORDERS;
  }
}

export function saveOrder(order: Order): Order {
  const currentOrders = getOrders();
  const updated = [order, ...currentOrders];
  fs.writeFileSync(ORDERS_FILE_PATH, JSON.stringify(updated, null, 2), "utf-8");
  return order;
}

export function updateOrderStatus(orderId: string, status: Order["status"]): boolean {
  const currentOrders = getOrders();
  const index = currentOrders.findIndex((o) => o.id === orderId);
  if (index === -1) return false;
  currentOrders[index].status = status;
  fs.writeFileSync(ORDERS_FILE_PATH, JSON.stringify(currentOrders, null, 2), "utf-8");
  return true;
}
