import { Subject } from '../db/index.js';

const addsubject = async (req, res) => {
  console.log('server/addsubject req.body', req.body)
  try {
    const { info, userId } = req.body;
    const findName = await Subject.findOne({ where: { name: info.lectureName } });
    if (findName) {
      throw new Error("이미 있는 과목입니다.")
    }
    await Subject.create({
      name: info.lectureName,
      prof: info.prof,
      room: info.classRoom, 
      userId: userId
    })

  } catch (error) {
    console.log(error)
    return res.status(500).send(error.message || "과목저장 에러발생")
  }
}

const getSubInfo = async (req, res) => {
  console.log('server/getSubInfo req.params', req.params)
  try {
    const { subjectId } = req.params;
    const findSubInfo = await Subject.findOne({ where: { id: subjectId } })
    if (findSubInfo) {
      res.json({
        name: findSubInfo.dataValues.name,
        prof: findSubInfo.dataValues.prof,
        room: findSubInfo.dataValues.room
      })
    } else {
      throw new Error("과목 찾기 실패")
    }
  } catch (error) {
    console.log(error)
    return res.status(500).send(error.message || "과목정보 가져오기 에러발생")
  }
}

const editSubject = async (req, res) => {
  console.log('server/editSubject req.body', req.body)
  try {
    const { info, id } = req.body;
    const result = await Subject.update({
      name: info.lectureName,
      prof: info.prof,
      room: info.classRoom,
    }, { where: { id: id } })
    if (!result) {
      throw new Error("과목정보 수정 에러발생")
    } else {
      res.send(200)
    }
  } catch (error) {
    console.log(error)
    return res.status(500).send(error.message || "과목정보 수정 에러발생")
  }
}

const allSubject = async (req, res) => {
  console.log('server/allSubject req.params', req.params)
  try {
    const { userId } = req.params;
    const findAllInfo = await Subject.findAll({ where: { userId: userId } })
    const sublist = findAllInfo.map(info => {
      const newList = {
        id: info.id,
        name: info.name,
        prof: info.prof,
        room: info.room,
        time: info.updatedAt
      }
      return newList
    })
    // const addplanlist = sublist.map(async(info)=>{
    //   const resplan = await Plan
    // })


  } catch (error) {
    console.log(error)
    return res.status(500).send(error.message || "전체과목 조회 에러")
  }
}

const subjectTitle = async (req, res) => {
  console.log('server/subjectTitle req.params', req.params)
  try {
    const { userId } = req.params
    const findAllTitle = await Subject.findAll({ where: { userId: userId } })
    const sublist = findAllTitle.map(info => {
      const newList = {
        id: info.id,
        name: info.name,
      }
      return newList
    })
    res.json(sublist)
  } catch (error) {
    console.log(error)
    return res.status(500).send(error.message || "과목명 조회 에러")
  }

}

export default {
  addsubject,
  getSubInfo,
  editSubject,
  allSubject,
  subjectTitle
}