import { HydratedDocument, ObjectId } from "mongoose";
import { FileInfo, IFileInfo, Mainimg, MainimgType } from "../models";
import fs from "fs/promises";
import { fileInfoCtrl } from "../controllers";
import formidable from "formidable";

export const createMainimg = async (mainimg: MainimgType, pic: IFileInfo) => {
  const newPic = await FileInfo.create({
    originalfilename: pic.originalfilename,
    newfilename: pic.newfilename,
    picturepath: pic.picturepath,
  });

  const newMainimg = await Mainimg.create({
    theme: mainimg.theme,
    city: mainimg.city,
    fileInfo: newPic._id,
    title: mainimg.title,
  });
  return newMainimg.populate("fileInfo");
};

export const getMainimg = async () => {
  const img = await Mainimg.find({}).populate("fileInfo");

  return img;
};

export const deleteOneMainimg = async (_id: string) => {
  const main = await Mainimg.findById(_id);
  if (!(main?.fileInfo === undefined)) {
    const ref = await FileInfo.findById(main.fileInfo._id);
    if (!(ref?.newfilename === undefined)) {
      await fs.unlink("../travel/uploads/" + ref?.newfilename);
    }
    await FileInfo.deleteOne({ _id: main.fileInfo._id });
    const res = await Mainimg.deleteOne({ _id: _id });
    return res;
  }
};

export const updateOneMainimg = async (
  _Id: string,
  theme: string,
  city: string,
  title: string,
  fileInfo?: formidable.File
) => {
  const newMainimg = await Mainimg.findById(_Id).populate<{
    fileInfo: IFileInfo;
  }>("fileInfo");
  // console.log("error2", newMainimg);
  if (!newMainimg) {
    throw new Error("mainimg가 존재하지 않습니다");
  }
  if (
    fileInfo?.originalFilename &&
    newMainimg?.fileInfo.originalfilename !== fileInfo?.originalFilename
  ) {
    // 같지 않으면 기존의 파일을 디스크에서 삭제한 후
    try {
      // console.log("picturepath", newMainimg.fileInfo.picturepath)
      await fs.unlink(newMainimg.fileInfo.picturepath);
    } catch (error) {
      console.log("error", error);
    }
    const mainimgAvatar = newMainimg.fileInfo as HydratedDocument<IFileInfo>;
    // 기존 fileinfo의 파일이름과 경로 변경 설정
    mainimgAvatar.originalfilename = fileInfo.originalFilename;
    mainimgAvatar.newfilename = fileInfo.newFilename;
    mainimgAvatar.picturepath = fileInfo.filepath;
    await mainimgAvatar.save();
  }

  newMainimg.theme = theme;
  newMainimg.city = city;
  newMainimg.title = title;
  await newMainimg.save();
  console.log("mainimg updated", newMainimg);
  return newMainimg;
};
