import { NextRequest, NextResponse } from "next/server";
import db from "@/lib/db";
import {
  DeleteFileById,
  UploadFIle,
} from "@/utils/backblaze";

import { getLogger } from "@/utils/logger";

const logger = getLogger("/api/user/[userUUID]");

enum Gender {
  MALE = "MALE",
  FEMALE = "FEMALE",
  OTHER = "OTHER",
}

function parseGender(value: string): Gender | undefined {
  if (value === "male") {
    return Gender.MALE;
  } else if (value === "female") {
    return Gender.FEMALE;
  } else if (value === "other") {
    return Gender.OTHER;
  } else {
    return undefined;
  }
}

export const PUT = async (
  req: NextRequest,
  { params }: { params: { uuid: string } }
) => {
  try {



    const formData = await req.formData();

    const name = formData.get("name") as string;
    const email = formData.get("email") as string;
    const mobile = formData.get("mobile") as string;
    const updated_by = formData.get("editedBy") as string;
    const genderValue = formData.get("gender") as string;
    const gender = parseGender(genderValue);
    if (!gender) {
      // Send error message to frontend
      return NextResponse.json(
        { error: "Invalid gender value" },
        { status: 400 }
      ); // throw new Error("Invalid gender value");
    }
    const dateOfBirth = new Date(formData.get("date_of_birth") as string);
    const imageFile = formData.get("profileImage") as File | null;

    // NEW CODE
    // Update the bucket ID to private bucket ID Name later

    const updateData: any = {
      email: email,
      updated_by,
      profile: {
        update: {
          full_name: name,
          date_of_birth: dateOfBirth,
          gender: gender,
          mobile_number: mobile,
        },
      },
    };
    // Overwrite old profile picture with new one later
    if (imageFile) {
      // Write the code to upload profile Image
      const fileName = imageFile.name;

      const fileType = imageFile.type;

      const fileContent = await imageFile.arrayBuffer();

      const response = await UploadFIle(
        fileName,
        fileType,
        fileContent,
        process.env.BACKBLAZE_BUCKET_ID ?? ""
      );

      if (response.success) {
        const userUuid = params.uuid;
        const user1 = await db.user.findUnique({
          where: { uuid: userUuid },
          select: {
            profile: {
              select: {
                picture: {
                  select: {
                    uuid: true,
                    file_name: true,
                    file_url: true,
                    file_id: true,
                  },
                },
              },
            },
          },
        });

        const fileId = response?.fileId;

        /*      logger.info("File ID - ", fileId)
              logger.info("File Name - ", response.UniqueFileName)*/

        const UniqueFileName = response?.UniqueFileName;

        const attachmentUuid = user1?.profile?.picture?.uuid;
        // console.log(attachmentUuid)
        const attachmentFileName = user1?.profile?.picture?.file_name;
        const attachmentFileId = user1?.profile?.picture?.file_id;

        if (attachmentUuid) {
          if (attachmentFileId && attachmentFileName) {
            const deleteResponse = await DeleteFileById(
              attachmentFileId as string,
              attachmentFileName as string,
              process.env.BACKBLAZE_BUCKET_ID as string
            );
          }

          const updatedProfilePicture = await db.attachments.update({
            where: { uuid: attachmentUuid },
            data: {
              original_name: imageFile!.name,
              file_name: UniqueFileName,
              file_url: response.fileUrl,
              file_type: fileType,
              file_id: fileId,
            },
          });

          // Delete the previous image using File ID
        } else {
          updateData.profile.update.picture = {
            create: {
              original_name: imageFile!.name,
              file_name: UniqueFileName,
              file_url: response.fileUrl,
              file_type: fileType,
              file_id: fileId,
            },
          };
        }
      }
    }

    const updatedUser = await db.user.update({
      where: { uuid: params.uuid },
      data: updateData,
    });

    return NextResponse.json(
      {
        user: updatedUser,
        message: "Updated Successfully",
      },
      { status: 201 }
    );
  } catch (error: any) {
    logger.error("An error occurred while updating user:", {
      userUuid: params.uuid,
      error: error.config.data,
    });
    return new NextResponse("Internal server error", { status: 500 });
  }
};


export async function GET(req: NextRequest, { params }: { params: { uuid: string } }) {
  const uuid = params.uuid

  try {
    const user = await db.user.findUnique({
      where: { uuid },
      select: {
        uuid: true,
        email: true,
        role: true,
        profile: {
          select: {
            full_name: true,
            mobile_number: true,
            gender: true,
            date_of_birth: true,
            address: true,
            orders: true,
            wishlist: true,
            payments: true,
            picture: true,
          },
        },
        accounts: {
          select: { provider: true },
        },
      },
    });

    if (!user) {
      return NextResponse.json({ error: "User not found" }, { status: 404 });
    }

    const addresses = user.profile?.address || [];

    if (addresses.length === 1 && !addresses[0].is_default) {
      await db.address.update({
        where: { id: addresses[0].id },
        data: { is_default: true },
      });
    }

    const provider = user.accounts?.[0]?.provider || null;

    return NextResponse.json(
      {
        User: {
          uuid: user.uuid,
          email: user.email,
          role: user.role,
          profile: user.profile,
        },
        UserAddresses: addresses,
        provider,
      },
      { status: 200 }
    );
  } catch (error) {
    logger.error(
      { userUuid: uuid, error },
      "An error occurred while fetching user data."
    );

    return NextResponse.json(
      { error: "An error occurred while fetching user data" },
      { status: 500 }
    );
  }
}

