import bcrypt from "bcryptjs";
import { HydratedDocument, ObjectId } from "mongoose";
import { IUser, Role, Post, User, FileInfo, IRole, IFileInfo } from "../models";
import fs from "fs/promises";
import formidable from "formidable";

export const createUser = async (user: IUser) => {
  // 비밀번호 암호화
  const hash = await bcrypt.hash(user.password, 10);
  // const newFileInfo = await FileInfo.create({});
  // 사용자 역할 추가: 기본값은 "user"
  let userRole = null;
  if (user.role) {
    userRole = await Role.findById(user.role);
  } else {
    userRole = await Role.findOne({ name: "user" });
  }
  const newUser = new User({
    email: user.email,
    name: user.name,
    password: hash,
    role: userRole,
    isNew: true,
    // fileInfo: newFileInfo._id,
  });
  const retUser = await newUser.save();
  return retUser;
};

export const findUserByEmail = async (
  email: string,
  includePassword: boolean = false
) => {
  let user;
  if (includePassword) {
    user = await User.findOne({ email })
      .select("+password")
      .populate<{ role: IRole }>("role");
  } else {
    user = await User.findOne({ email }).populate<{ role: IRole }>("role");
  }
  return user;
};

export const findUserByPostId = async (postId: string) => {
  const post = await Post.findOne({ _id: postId }).populate("user");
  return post?.user;
};

export const getProfile = async (userId: string) => {
  const profile = await User.findById(userId).populate("avatar");
  return profile; //이름 수정
};

export const getUsers = async () => {
  const users = await User.find({});
  return users;
};

export const isUser = async (email: string) => {
  const user = await User.findOne({ email });
  if (user) {
    return true;
  } else {
    return false;
  }
};

export const isValidUserId = async (userId: string) => {
  const user = await User.findById(userId);
  if (user) {
    return true;
  } else {
    return false;
  }
};

export const updateProfile = async (
  userId: ObjectId,
  name: string,
  avatar: formidable.File
) => {
  const user = await User.findById(userId).populate<{ avatar: IFileInfo }>(
    "avatar"
  );
  console.log("user in update profile", user, avatar);
  if (!user) {
    throw new Error("사용자가 존재하지 않습니다");
  }
  if (avatar) {
    if (!user.avatar) {
      // 사용자의 아바타가 존재하지 않으면 생성
      const file = await FileInfo.create({
        originalfilename: avatar.originalFilename,
        newfilename: avatar.newFilename,
        picturepath: avatar.filepath,
      });
      user.avatar = file;
    } else {
      // 아바타에 같은 원래파일이름이 존재하는지 확인
      // 같으면 파일 수정하지 않고 통과
      if (
        avatar.originalFilename &&
        user.avatar.originalfilename !== avatar.originalFilename
      ) {
        // 같지 않으면 기존의 파일을 디스크에서 삭제한 후
        try {
          await fs.unlink(user.avatar.picturepath);
        } catch (error) {
          console.log("error", error);
        }
        const userAvatar = user.avatar as HydratedDocument<IFileInfo>;
        // 기존 아바타 fileinfo의 파일이름과 경로 변경 설정
        userAvatar.originalfilename = avatar.originalFilename;
        userAvatar.newfilename = avatar.newFilename;
        userAvatar.picturepath = avatar.filepath;
        await userAvatar.save();
      }
    }
  }
  user.name = name;
  await user.save();
  console.log("user updated", user);
  return user;

  // if (!(profile?.avatar === undefined)) {
  //   if (originalfilename === null) {
  //     await FileInfo.findByIdAndUpdate(profile.avatar._id, {
  //       nickname: nickname,
  //     });
  //   } else if (nickname === "") {
  //     const ref = FileInfo.findById(profile.avatar._id);
  //     console.log(ref);

  //     await FileInfo.findByIdAndUpdate(profile.avatar._id, {
  //       originalfilename: originalfilename,
  //       newfilename: newfilename,
  //       picturepath: picturepath,
  //     });
  //   } else {
  //     const ref = await FileInfo.findByIdAndUpdate(profile.avatar._id, {
  //       originalfilename: originalfilename,
  //       newfilename: newfilename,
  //       picturepath: picturepath,
  //       nickname: nickname,
  //     });
  //   }
  // }
};

export const deleteUser = async (userId: string) => {
  const user = await User.findById(userId);
  if (!(user?.avatar === undefined)) {
    const ref = await FileInfo.findById(user.avatar._id);
    if (!(ref?.newfilename === undefined)) {
      await fs.unlink("../travel/uploads/" + ref?.newfilename);
    }
    await FileInfo.deleteOne({ _id: user.avatar._id });
    const finish = await User.deleteOne({ _id: userId });
    return finish;
  }
};
