import { User } from "../models/index.js";
import jwt from "jsonwebtoken";
import config from "../config/app.config.js";
import isLength from "validator/lib/isLength.js";
import multer from "multer";

const uploadimg = multer({ dest: "uploads/" });

const imgUpload = uploadimg.fields([{ name: "img", maxCount: 1 }]);

const update = async (req, res) => {
  try {
    console.log("id:", req.body.id);
    const id = req.body.id;
    const avatar = req.files["img"][0];
    const img = avatar.filename;
    console.log(img);
    await User.update({ img: img }, { where: { id: id } });
    res.json(img);
  } catch (error) {
    console.log(error);
    res.status(500).send("이미지 업데이트 실패");
  }
};
const getUser = async (req, res) => {
  const user = await User.findOne({ where: { id: req.params.id } });
  res.json(user)
};

const updateinfo = async (req, res) => {
  console.log(req.body);
  const { id, name, email, phone, img } = req.body;
  console.log("id:", id);
  const A = {
    name: name,
    email: email,
    phone: phone,
    img: img,
  };
  await User.update(A, { where: { id: id } });
  const user = await User.findOne({ where: { id: id } });
  console.log('user:',user)
};
const login = async (req, res) => {
  try {
    const { email, password } = req.body
    const user = await User.findOne({ where: { email: email } })
    if (!user) {
      return res.status(422).send(`${email} 사용자가 존재하지 않습니다.`);
    } else {
      const passworMatch = await user.comparePassword(password);
      if (passworMatch) {
        const token = jwt.sign({ userID: user.id }, config.jwtSecret, {
          expiresIn: config.jwtExpires,
        });
        res.cookie(config.cookieName, token, {
          path: "/",
          httpOnly: true,
          secure: true,
        });
        res.json(user);
      } else {
        res.status(401).send("비밀번호가 일치하지 않습니다.");
      }
    }
  } catch (error) {
    return res.status(500).send('로그인 중 에러')
  }
};

const signup = async (req, res) => {
  try {
    // console.log('sign up= ', req.body)
    const { name, email, password, gender, phone } = req.body
    const id = Math.floor(Math.random() * (9999 - 1000) + 1000)
    // console.log('id:', id)
    const Id = await User.findOne({ where: { id: id } })
    // console.log('Id 중복확인:', Id)
    while (Id) {
      const id = Math.floor(Math.random() * (9999 - 1000) + 1000);
      const Id = await User.findOne({ where: { id: id } });
    }

    const user = await User.findOne({ where: { email: email } });
    if (user)
      return res.status(422).send(`${email} 이미 존재하는 사용자입니다.`);

    if (!isLength(name, { min: 3, max: 10 })) {
      return res.status(422).send("이름은 3-10자 사이입니다");
    } else if (!isLength(password, { min: 6 })) {
      return res.status(422).send("비밀번호는 6자이상 입니다");
    } else if (!isLength(email, { min: 3, max: 10 })) {
      return res.status(422).send("아이디는 3-10자 사이입니다");
    }
    const newUser = await User.create({
      id: id,
      name: name,
      email: email,
      password: password,
      gender: gender,
      phone: phone,
    })
  } catch (error) {
    console.log(error);
    return res.status(500).send("회원가입 중 에러");
  }
};

const logout = (req, res) => {
  res.clearCookie("token");
  res.send("Logout Successful");
};

export default {
  getUser,
  login,
  signup,
  logout,
  imgUpload,
  update,
  updateinfo,
};
