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.body', 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 || "과목정보 수정 에러발생")
  }
}

export default {
  addsubject,
  getSubInfo,
  editSubject
}