import { Todo } from '../db/index.js';
import sequelize from 'sequelize';

const { Op } = sequelize

const findbyId = async (req, res, next) => {
  try {
    const userId = req.userId
    const { todoId } = req.query
    if (todoId) {
      console.log(" findbyId todoId가 있을 때 실행", todoId)
      const findTodo = await Todo.findOne({ where: { [Op.and]: [{ id: todoId }, { userId: userId }] }, attributes: ['id', ['title', 'todoTitle'], ['date', 'todoDate'], 'done'] })
      if (!findTodo) throw new Error("해당 todo를 찾지 못했습니다.")
      req.todoOne = findTodo
    }
    next()
  } catch (error) {
    return res.status(500).send(error.message || "todo 가져오는 중 에러 발생")
  }
}

const findbyDate = async (req, res, next) => {
  try {
    const userId = req.userId
    const { date } = req.query
    if (date) {
      console.log(" findbydate 날짜가 있을 때 실행", date, userId)
      const findList = await Todo.findAll({ where: { [Op.and]: [{ date: { [Op.eq]: date } }, { userId: userId }] }, attributes: ['id', ['title', 'todoTitle'], ['date', 'todoDate'], 'done'] })
      console.log("find==", findList)
      req.todoList = findList
    }
    next()
  } catch (error) {
    return res.status(500).send(error.message || "todo 가져오는 중 에러 발생")
  }
}

const findforPercent = async (req, res) => {
  try {
    let doneTodo = null
    const userId = req.userId
    const { start, end } = req.query
    if (end) {
      console.log("week 실행하냐")
      const findList= await Todo.findAndCountAll({ where: { [Op.and]: [{ userId: userId }, { date: [start, end] }] }, group: ['date'] })
      console.log("week findList",findList)
    } else {
      let percent = 0
      console.log("findforPercent end 없음")
      const nonCheck = await Todo.findAndCountAll({ where: { [Op.and]: [{ date: { [Op.eq]: start } }, { userId: userId }, { done: false }] }, order: [['updatedAt', "DESC"]] })
      const check = await Todo.findAndCountAll({ where: { [Op.and]: [{ date: { [Op.eq]: start } }, { userId: userId }, { done: true }] }, order: [['updatedAt', "DESC"]] })
      let total = nonCheck.count + check.count
      check.rows.forEach(el => nonCheck.rows.push(el.dataValues))
      console.log("non", nonCheck)
      if (total === 0) percent = 0
      else percent = Math.round((check.count / total) * 100)
      return res.json({ percent: percent, list: nonCheck.rows })
    }
  } catch (error) {
    return res.status(500).send(error.message || "todo 가져오는 중 에러 발생")
  }
}

const create = async (req, res) => {
  try {
    const userId = req.userId
    const { todoTitle, todoDate } = req.body
    const newTodo = await Todo.create({ title: todoTitle, date: todoDate, userId: userId })
    return res.json(newTodo)
  } catch (error) {
    return res.status(500).send(error.message || "todo 등록 중 에러 발생")
  }
}

const edit = async (req, res) => {
  try {
    let updated = null
    const userId = req.userId
    const { todoId } = req.query
    const { todoTitle, todoDate } = req.body
    if (todoTitle) updated = await Todo.update({ title: todoTitle, date: todoDate }, { where: { [Op.and]: [{ id: todoId }, { userId: userId }] } })
    else updated = await Todo.update({ date: todoDate }, { where: { [Op.and]: [{ id: todoId }, { userId: userId }] } })
    if (!updated) throw new Error("해당 todo의 일부 정보를 수정하는데 실패하였습니다.")
    else return res.send(200)
  } catch (error) {
    return res.status(500).send(error.message || "todo 수정 중 에러 발생")
  }
}

const remove = async (req, res) => {
  try {
    const userId = req.userId
    const { todoId } = req.query
    const deleted = await Todo.destroy({ where: { [Op.and]: [{ id: todoId }, { userId: userId }] } })
    if (!deleted) throw new Error("해당 todo를 삭제하는데 실패하였습니다.")
    else return res.send(200)
  } catch (error) {
    return res.status(500).send(error.message || "todo 삭제 중 에러 발생")
  }
}

const getParams = async (req, res, next) => {
  try {
    const { userId } = req.params
    req.userId = userId
    next()
  } catch (error) {
    return res.status(500).send(error.message || "todo 가져오는 중 에러 발생")
  }
}

const send = async (req, res) => {
  try {
    const result = req.todoOne || req.todoList
    return res.json(result)
  } catch (error) {
    return res.status(500).send(error.message || "todo 가져오는 중 에러 발생")
  }
}

export default {
  findbyId,
  findbyDate,
  findforPercent,
  create,
  edit,
  remove,
  getParams,
  send
}