import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { randomUUID } from "crypto";
import {
  order_orderType,
  order_paymentMethod,
} from "@prisma/client";

/*
============================================================
TYPES
============================================================
*/

interface IncomingOrderItem {
  productId: string;
  productName?: string;
  price?: number;
  quantity: number;
}

interface CreateOrderBody {
  firstName?: string;
  lastName?: string;
  phone?: string;
  email?: string;
  address?: string;
  notes?: string;
  orderType?: string;
  paymentMethod?: string;
  deliveryZoneId?: string | null;
  items?: IncomingOrderItem[];
}

/*
============================================================
CONSTANTES
============================================================
*/

const VALID_ORDER_TYPES = Object.values(
  order_orderType
);

const VALID_PAYMENT_METHODS = Object.values(
  order_paymentMethod
);

/*
============================================================
UTILITAIRES
============================================================
*/

function isValidOrderType(
  value: unknown
): value is order_orderType {
  return (
    typeof value === "string" &&
    VALID_ORDER_TYPES.includes(
      value as order_orderType
    )
  );
}

function isValidPaymentMethod(
  value: unknown
): value is order_paymentMethod {
  return (
    typeof value === "string" &&
    VALID_PAYMENT_METHODS.includes(
      value as order_paymentMethod
    )
  );
}

/*
============================================================
GET /api/orders

Récupérer toutes les commandes
============================================================
*/

export async function GET() {
  try {
    const orders =
      await prisma.order.findMany({
        orderBy: {
          createdAt: "desc",
        },

        include: {
          items: true,

          deliveryZone: {
            select: {
              name: true,
            },
          },
        },
      });

    const formattedOrders =
      orders.map((order) => ({
        id: order.id,

        orderNumber:
          order.orderNumber,

        firstName:
          order.firstName,

        lastName:
          order.lastName,

        phone:
          order.phone,

        email:
          order.email,

        address:
          order.address,

        notes:
          order.notes,

        deliveryZone:
          order.deliveryZone?.name ??
          null,

        orderType:
          order.orderType,

        paymentMethod:
          order.paymentMethod,

        status:
          order.status,

        subtotal:
          order.subtotal,

        deliveryFee:
          order.deliveryFee,

        total:
          order.total,

        createdAt:
          order.createdAt,

        updatedAt:
          order.updatedAt,

        items:
          order.items.map(
            (item) => ({
              id: item.id,

              productId:
                item.productId,

              productName:
                item.productName,

              price:
                item.price,

              quantity:
                item.quantity,
            })
          ),
      }));

    return NextResponse.json({
      success: true,

      orders:
        formattedOrders,
    });
  } catch (error) {
    console.error(
      "Erreur GET /api/orders :",
      error
    );

    return NextResponse.json(
      {
        success: false,

        message:
          "Impossible de récupérer les commandes.",
      },
      {
        status: 500,
      }
    );
  }
}

/*
============================================================
POST /api/orders

Créer une nouvelle commande

IMPORTANT :

Les prix envoyés par le frontend ne sont PAS considérés
comme fiables.

Le serveur récupère les vrais produits depuis Prisma
et recalcule :

- le prix unitaire
- le sous-total
- les frais de livraison
- le total

Cela empêche un utilisateur de modifier le prix depuis
le navigateur.
============================================================
*/

export async function POST(
  request: Request
) {
  try {
    /*
    ============================================================
    LECTURE DU BODY
    ============================================================
    */

    let body: CreateOrderBody;

    try {
      body =
        await request.json();
    } catch {
      return NextResponse.json(
        {
          success: false,

          message:
            "Le corps de la requête est invalide.",
        },
        {
          status: 400,
        }
      );
    }

    const {
      firstName,
      lastName,
      phone,
      email,
      address,
      notes,
      orderType,
      paymentMethod,
      deliveryZoneId,
      items,
    } = body;

    /*
    ============================================================
    VALIDATION INFORMATIONS CLIENT
    ============================================================
    */

    if (
      typeof firstName !== "string" ||
      !firstName.trim()
    ) {
      return NextResponse.json(
        {
          success: false,

          message:
            "Le prénom est obligatoire.",
        },
        {
          status: 400,
        }
      );
    }

    if (
      typeof lastName !== "string" ||
      !lastName.trim()
    ) {
      return NextResponse.json(
        {
          success: false,

          message:
            "Le nom est obligatoire.",
        },
        {
          status: 400,
        }
      );
    }

    if (
      typeof phone !== "string" ||
      !phone.trim()
    ) {
      return NextResponse.json(
        {
          success: false,

          message:
            "Le numéro de téléphone est obligatoire.",
        },
        {
          status: 400,
        }
      );
    }

    /*
    ============================================================
    VALIDATION TYPE DE COMMANDE
    ============================================================
    */

    if (
      !isValidOrderType(
        orderType
      )
    ) {
      return NextResponse.json(
        {
          success: false,

          message:
            "Le type de commande est invalide.",
        },
        {
          status: 400,
        }
      );
    }

    /*
    ============================================================
    VALIDATION MOYEN DE PAIEMENT
    ============================================================
    */

    if (
      !isValidPaymentMethod(
        paymentMethod
      )
    ) {
      return NextResponse.json(
        {
          success: false,

          message:
            "Le moyen de paiement est invalide.",
        },
        {
          status: 400,
        }
      );
    }

    /*
    ============================================================
    VALIDATION ARTICLES
    ============================================================
    */

    if (
      !Array.isArray(items) ||
      items.length === 0
    ) {
      return NextResponse.json(
        {
          success: false,

          message:
            "La commande doit contenir au moins un article.",
        },
        {
          status: 400,
        }
      );
    }

    /*
    ============================================================
    VALIDATION DES ARTICLES ENTRANTS
    ============================================================
    */

    for (const item of items) {
      if (
        !item ||
        typeof item.productId !==
          "string" ||
        !item.productId.trim()
      ) {
        return NextResponse.json(
          {
            success: false,

            message:
              "Un article possède un identifiant produit invalide.",
          },
          {
            status: 400,
          }
        );
      }

      const quantity =
        Number(
          item.quantity
        );

      if (
        !Number.isInteger(
          quantity
        ) ||
        quantity <= 0
      ) {
        return NextResponse.json(
          {
            success: false,

            message:
              "La quantité d'un article est invalide.",
          },
          {
            status: 400,
          }
        );
      }

      /*
      Limite de sécurité.

      On évite qu'une requête malveillante tente
      de commander des milliers d'unités.
      */

      if (
        quantity > 100
      ) {
        return NextResponse.json(
          {
            success: false,

            message:
              "La quantité maximale par article est de 100.",
          },
          {
            status: 400,
          }
        );
      }
    }

    /*
    ============================================================
    VÉRIFICATION TYPE DE COMMANDE
    ============================================================
    */

    if (
      orderType ===
        order_orderType.DELIVERY &&
      !deliveryZoneId
    ) {
      return NextResponse.json(
        {
          success: false,

          message:
            "Une zone de livraison est obligatoire pour une commande en livraison.",
        },
        {
          status: 400,
        }
      );
    }

    /*
    ============================================================
    VÉRIFICATION ZONE DE LIVRAISON
    ============================================================
    */

    let deliveryZone:
      | {
          id: string;
          name: string;
          fee: number;
          isActive: boolean;
        }
      | null = null;

    if (
      deliveryZoneId
    ) {
      deliveryZone =
        await prisma.deliveryzone.findUnique(
          {
            where: {
              id: deliveryZoneId,
            },

            select: {
              id: true,
              name: true,
              fee: true,
              isActive: true,
            },
          }
        );

      if (
        !deliveryZone
      ) {
        return NextResponse.json(
          {
            success: false,

            message:
              "La zone de livraison sélectionnée n'existe pas.",
          },
          {
            status: 400,
          }
        );
      }

      if (
        !deliveryZone.isActive
      ) {
        return NextResponse.json(
          {
            success: false,

            message:
              "Cette zone de livraison n'est plus disponible.",
          },
          {
            status: 400,
          }
        );
      }
    }

    /*
    ============================================================
    RÉCUPÉRATION DES PRODUITS DEPUIS LA BASE
    ============================================================

    IMPORTANT :

    Nous ignorons complètement :

    - item.price
    - item.productName

    envoyés par le navigateur.

    Le serveur récupère les vraies informations depuis Prisma.
    ============================================================
    */

    const productIds =
      [
        ...new Set(
          items.map(
            (item) =>
              item.productId
          )
        ),
      ];

    const products =
      await prisma.product.findMany(
        {
          where: {
            id: {
              in: productIds,
            },
          },

          select: {
            id: true,
            name: true,
            price: true,
            isAvailable: true,
          },
        }
      );

    /*
    ============================================================
    VÉRIFICATION QUE TOUS LES PRODUITS EXISTENT
    ============================================================
    */

    if (
      products.length !==
      productIds.length
    ) {
      return NextResponse.json(
        {
          success: false,

          message:
            "Un ou plusieurs produits de la commande n'existent plus.",
        },
        {
          status: 400,
        }
      );
    }

    /*
    ============================================================
    VÉRIFICATION DISPONIBILITÉ PRODUITS
    ============================================================
    */

    const unavailableProducts =
      products.filter(
        (product) =>
          !product.isAvailable
      );

    if (
      unavailableProducts.length >
      0
    ) {
      return NextResponse.json(
        {
          success: false,

          message:
            `Le ou les produits suivants ne sont plus disponibles : ${unavailableProducts
              .map(
                (product) =>
                  product.name
              )
              .join(", ")}`,
        },
        {
          status: 400,
        }
      );
    }

    /*
    ============================================================
    MAP PRODUITS
    ============================================================
    */

    const productMap =
      new Map(
        products.map(
          (product) => [
            product.id,
            product,
          ]
        )
      );

    /*
    ============================================================
    CALCUL SOUS-TOTAL SERVEUR
    ============================================================
    */

    let numericSubtotal =
      0;

    const validatedItems =
      items.map(
        (item) => {
          const product =
            productMap.get(
              item.productId
            );

          if (
            !product
          ) {
            throw new Error(
              `Produit introuvable : ${item.productId}`
            );
          }

          const quantity =
            Number(
              item.quantity
            );

          const price =
            Number(
              product.price
            );

          numericSubtotal +=
            price *
            quantity;

          return {
            productId:
              product.id,

            productName:
              product.name,

            price,

            quantity,
          };
        }
      );

    /*
    ============================================================
    CALCUL FRAIS DE LIVRAISON
    ============================================================
    */

    const numericDeliveryFee =
      orderType ===
        order_orderType.DELIVERY &&
      deliveryZone
        ? Number(
            deliveryZone.fee
          )
        : 0;

    /*
    ============================================================
    CALCUL TOTAL SERVEUR
    ============================================================
    */

    const numericTotal =
      numericSubtotal +
      numericDeliveryFee;

    /*
    ============================================================
    VALIDATION ADRESSE POUR LIVRAISON
    ============================================================
    */

    if (
      orderType ===
        order_orderType.DELIVERY &&
      (!address ||
        !address.trim())
    ) {
      return NextResponse.json(
        {
          success: false,

          message:
            "Une adresse de livraison est obligatoire.",
        },
        {
          status: 400,
        }
      );
    }

    /*
    ============================================================
    NUMÉRO UNIQUE DE COMMANDE
    ============================================================
    */

    const orderNumber =
      `HH-${Date.now()}-${randomUUID()
        .slice(0, 6)
        .toUpperCase()}`;

    /*
    ============================================================
    CRÉATION COMMANDE

    La nested write Prisma permet de créer :

    1. La commande
    2. Tous les articles associés

    dans une même opération transactionnelle.
    ============================================================
    */

    const order =
      await prisma.order.create(
        {
          data: {
            orderNumber,

            firstName:
              firstName.trim(),

            lastName:
              lastName.trim(),

            phone:
              phone.trim(),

            email:
              typeof email ===
                "string" &&
              email.trim()
                ? email.trim()
                : null,

            address:
              typeof address ===
                "string" &&
              address.trim()
                ? address.trim()
                : null,

            notes:
              typeof notes ===
                "string" &&
              notes.trim()
                ? notes.trim()
                : null,

            orderType,

            paymentMethod,

            /*
            IMPORTANT :

            Ces valeurs sont calculées
            par le serveur.
            */

            subtotal:
              numericSubtotal,

            deliveryFee:
              numericDeliveryFee,

            total:
              numericTotal,

            deliveryZoneId:
              orderType ===
                order_orderType.DELIVERY
                ? deliveryZoneId
                : null,

            items: {
              create:
                validatedItems,
            },
          },

          include: {
            items: true,

            deliveryZone: true,
          },
        }
      );

    /*
    ============================================================
    RÉPONSE
    ============================================================
    */

    return NextResponse.json(
      {
        success: true,

        message:
          "Commande créée avec succès.",

        order,
      },
      {
        status: 201,
      }
    );
  } catch (error) {
    console.error(
      "Erreur POST /api/orders :",
      error
    );

    return NextResponse.json(
      {
        success: false,

        message:
          "Impossible de créer la commande.",
      },
      {
        status: 500,
      }
    );
  }
}