import { Types, ObjectId } from "mongoose";
import fs from "fs/promises";
import { Post, PostType } from "../models";
import { FileInfo, IFileInfo } from "../models";

//Create
export const createPostRow = async (post: PostType) => {
  const newPostRow = await Post.create({
    title: post.title,
    text: post.text,
    theme: post.theme,
    city: post.city,
    user: post.user,
    date: post.date,
    counts: 0,
    file: post.file,
  });
  return newPostRow;
};

export const createFilesRow = async (
  originalfilename?: string | null,
  newfilename?: string,
  picturepath?: string
) => {
  const newFileRow = await FileInfo.create({
    originalfilename: originalfilename,
    newfilename: newfilename,
    picturepath: picturepath,
  });
  // console.log("check", newFileRow);
  return newFileRow._id;
};

//Read
export const getPosts = async () => {
  const posts = await Post.find()
    .populate("file")
    .populate("user")
    .sort({ date: -1 });
  return posts;
};

//Update
export const addOneCount = async (_id: string, counts: number) => {
  const updatedPost = await Post.findOneAndUpdate(
    { _id: _id },
    { counts: counts },
    { new: true }
  );
  return updatedPost;
};

export const updatePostRow = async (post: PostType, postId: string) => {
  const newPost = await Post.findOneAndUpdate(
    { _id: postId },
    {
      title: post.title,
      text: post.text,
      theme: post.theme,
      city: post.city,
      date: post.date,
      file: post.file,
    },
    { new: true }
  ).populate("file");
  return newPost;
};

export const getFilesByPostId = async (postId: string) => {
  const files = await Post.findOne({ _id: postId }).populate("file");
  return files?.file; //file Types.ObjectId[]
};

export const getOriginalFileName = async (_id: Types.ObjectId) => {
  const file = await FileInfo.findOne({ _id: _id });
  return file?.originalfilename;
};

export const updatedFileId = async (_id: string) => {
  const updatedFile = await Post.findOne({ _id: _id }).populate("file");
  return updatedFile?.file;
};

export const findByName = async (originalfilename: string) => {
  const fileId = await FileInfo.find({ originalfilename });
  return fileId;
};

//Delete
export const deletePost = async (_id: string) => {
  const post = await Post.findById(_id);
  if (!(post?.file === undefined)) {
    for (var i = 0; i < post.file.length; i++) {
      const fileId = post.file[i];
      const ref = await FileInfo.findById(fileId);
      if (!(ref?.newfilename === undefined)) {
        await fs.unlink("../travel/uploads/" + ref?.newfilename);
      }
      await FileInfo.deleteOne({ _id: fileId });
    }
    const res = await Post.deleteOne({ _id: _id });
    return res;
  }
};

export const deleteFileByName = async (originalfilename: string) => {
  const deleteFile = await FileInfo.deleteOne({ originalfilename });
  return deleteFile;
};
