import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { writeFile, mkdir, unlink } from "fs/promises";
import path from "path";

/**
 * GET
 * Récupère un produit par son ID
 */
export async function GET(
  request: Request,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await context.params;

    const product = await prisma.product.findUnique({
      where: {
        id,
      },
      include: {
        category: true,
      },
    });

    if (!product) {
      return NextResponse.json(
        {
          success: false,
          message: "Produit introuvable.",
        },
        {
          status: 404,
        }
      );
    }

    return NextResponse.json({
      success: true,
      product,
    });
  } catch (error) {
    console.error(
      "Erreur récupération produit :",
      error
    );

    return NextResponse.json(
      {
        success: false,
        message:
          "Impossible de récupérer le produit.",
      },
      {
        status: 500,
      }
    );
  }
}

/**
 * PUT
 * Modifie complètement un produit
 * avec possibilité de remplacer son image
 */
export async function PUT(
  request: Request,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await context.params;

    // Récupérer le produit existant
    const existingProduct =
      await prisma.product.findUnique({
        where: {
          id,
        },
      });

    if (!existingProduct) {
      return NextResponse.json(
        {
          success: false,
          message: "Produit introuvable.",
        },
        {
          status: 404,
        }
      );
    }

    // Récupérer le formulaire
    const formData = await request.formData();

    const name = formData.get("name");
    const description =
      formData.get("description");
    const price = formData.get("price");
    const categoryId =
      formData.get("categoryId");

    const isAvailable =
      formData.get("isAvailable") === "on";

    const isFeatured =
      formData.get("isFeatured") === "on";

    const imageFile =
      formData.get("image");

    // Vérification des champs obligatoires
    if (
      !name ||
      !categoryId ||
      !price
    ) {
      return NextResponse.json(
        {
          success: false,
          message:
            "Le nom, le prix et la catégorie sont obligatoires.",
        },
        {
          status: 400,
        }
      );
    }

    // Vérifier que le prix est valide
    const numericPrice = Number(price);

    if (
      Number.isNaN(numericPrice) ||
      numericPrice < 0
    ) {
      return NextResponse.json(
        {
          success: false,
          message:
            "Le prix indiqué est invalide.",
        },
        {
          status: 400,
        }
      );
    }

    // Vérifier la catégorie
    const category =
      await prisma.category.findUnique({
        where: {
          id: String(categoryId),
        },
      });

    if (!category) {
      return NextResponse.json(
        {
          success: false,
          message:
            "La catégorie sélectionnée n'existe pas.",
        },
        {
          status: 400,
        }
      );
    }

    // Conserver l'ancienne image
    let imagePath =
      existingProduct.image;

    /**
     * Si une nouvelle image est envoyée,
     * on remplace l'ancienne
     */
    if (
      imageFile &&
      imageFile instanceof File &&
      imageFile.size > 0
    ) {
      const allowedTypes = [
        "image/jpeg",
        "image/jpg",
        "image/png",
        "image/webp",
      ];

      if (
        !allowedTypes.includes(
          imageFile.type
        )
      ) {
        return NextResponse.json(
          {
            success: false,
            message:
              "Format d'image non autorisé.",
          },
          {
            status: 400,
          }
        );
      }

      // Limite 5 Mo
      if (
        imageFile.size >
        5 * 1024 * 1024
      ) {
        return NextResponse.json(
          {
            success: false,
            message:
              "L'image ne doit pas dépasser 5 Mo.",
          },
          {
            status: 400,
          }
        );
      }

      // Dossier uploads
      const uploadDir =
        path.join(
          process.cwd(),
          "public",
          "uploads",
          "products"
        );

      await mkdir(
        uploadDir,
        {
          recursive: true,
        }
      );

      // Extension
      const extension =
        path.extname(
          imageFile.name
        ) || ".jpg";

      // Nom unique
      const fileName =
        `${Date.now()}-${Math.random()
          .toString(36)
          .substring(2, 10)}` +
        extension;

      const filePath =
        path.join(
          uploadDir,
          fileName
        );

      // Conversion du fichier
      const bytes =
        await imageFile.arrayBuffer();

      const buffer =
        Buffer.from(bytes);

      // Enregistrement
      await writeFile(
        filePath,
        buffer
      );

      // Nouvelle URL
      imagePath =
        `/uploads/products/${fileName}`;

      /**
       * Supprimer l'ancienne image
       * si elle appartient à notre dossier uploads
       */
      if (
        existingProduct.image &&
        existingProduct.image.startsWith(
          "/uploads/products/"
        )
      ) {
        const oldImagePath =
          path.join(
            process.cwd(),
            "public",
            existingProduct.image
          );

        try {
          await unlink(
            oldImagePath
          );
        } catch {
          console.warn(
            "Ancienne image introuvable."
          );
        }
      }
    }

    // Mise à jour du produit
    const product =
      await prisma.product.update({
        where: {
          id,
        },
        data: {
          name: String(name),

          description:
            description
              ? String(description)
              : null,

          price:
            numericPrice,

          image:
            imagePath,

          isAvailable,

          isFeatured,

          categoryId:
            String(categoryId),
        },

        include: {
          category: true,
        },
      });

    return NextResponse.json({
      success: true,
      message:
        "Produit modifié avec succès.",
      product,
    });
  } catch (error) {
    console.error(
      "Erreur modification produit :",
      error
    );

    return NextResponse.json(
      {
        success: false,
        message:
          "Impossible de modifier le produit.",
      },
      {
        status: 500,
      }
    );
  }
}

/**
 * PATCH
 * Modifie uniquement la disponibilité
 * ou la mise à la une d'un produit
 */
export async function PATCH(
  request: Request,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await context.params;

    // Récupérer le produit
    const existingProduct =
      await prisma.product.findUnique({
        where: {
          id,
        },
      });

    if (!existingProduct) {
      return NextResponse.json(
        {
          success: false,
          message: "Produit introuvable.",
        },
        {
          status: 404,
        }
      );
    }

    // Lire les données JSON
    const body = await request.json();

    const data: {
      isAvailable?: boolean;
      isFeatured?: boolean;
    } = {};

    // Vérifier isAvailable
    if (
      typeof body.isAvailable ===
      "boolean"
    ) {
      data.isAvailable =
        body.isAvailable;
    }

    // Vérifier isFeatured
    if (
      typeof body.isFeatured ===
      "boolean"
    ) {
      data.isFeatured =
        body.isFeatured;
    }

    // Vérifier qu'au moins un champ
    // est à modifier
    if (
      Object.keys(data).length === 0
    ) {
      return NextResponse.json(
        {
          success: false,
          message:
            "Aucune modification valide n'a été fournie.",
        },
        {
          status: 400,
        }
      );
    }

    // Mise à jour
    const product =
      await prisma.product.update({
        where: {
          id,
        },
        data,
        include: {
          category: true,
        },
      });

    return NextResponse.json({
      success: true,
      message:
        "Produit mis à jour avec succès.",
      product,
    });
  } catch (error) {
    console.error(
      "Erreur mise à jour partielle du produit :",
      error
    );

    return NextResponse.json(
      {
        success: false,
        message:
          "Impossible de mettre à jour le produit.",
      },
      {
        status: 500,
      }
    );
  }
}

/**
 * DELETE
 * Supprime un produit
 */
export async function DELETE(
  request: Request,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await context.params;

    // Récupérer le produit
    const product =
      await prisma.product.findUnique({
        where: {
          id,
        },
      });

    if (!product) {
      return NextResponse.json(
        {
          success: false,
          message:
            "Produit introuvable.",
        },
        {
          status: 404,
        }
      );
    }

    /**
     * Supprimer l'image
     * associée au produit
     */
    if (
      product.image &&
      product.image.startsWith(
        "/uploads/products/"
      )
    ) {
      const imagePath =
        path.join(
          process.cwd(),
          "public",
          product.image
        );

      try {
        await unlink(
          imagePath
        );
      } catch {
        console.warn(
          "Image du produit introuvable."
        );
      }
    }

    // Supprimer le produit
    await prisma.product.delete({
      where: {
        id,
      },
    });

    return NextResponse.json({
      success: true,
      message:
        "Produit supprimé avec succès.",
    });
  } catch (error) {
    console.error(
      "Erreur suppression produit :",
      error
    );

    return NextResponse.json(
      {
        success: false,
        message:
          "Impossible de supprimer le produit.",
      },
      {
        status: 500,
      }
    );
  }
}
