import { Request, Router } from "express";
import UserService from "../services/user-services";
import { User } from "common/common-types";
import { omit } from "lodash";

const router = Router();

const getKnex = (req: Request) => req.app.get("knex");

/** Creating user */
router.post("/", async (req, res) => {
  const knex = getKnex(req);

  try {
    const userService = new UserService(knex);
    const user = await userService.create(req.body);

    console.log("user :", user);
  } catch (err) {
    res.send(`An error has occured: ${err}`);
  }
});

/** Updating user */
router.put("/:login", async (req, res) => {
  const knex = getKnex(req);

  try {
    const userService = new UserService(knex);
    const user = await userService.update(req.params.id, req.body);
    res.send(`User with login ${user.login} was succesfully updated`);
  } catch (err) {
    res.status(400).send(`An error has occured: ${err}`);
  }
});

router.get("/", async (req, res) => {
  const knex = getKnex(req);

  try {
    const userService = new UserService(knex);
    const allUsers = await userService.getAll();

    res.status(200).json(allUsers);
  } catch (err) {
    res.status(400).send(`An error has occured: ${err}`);
  }
});

router.get("/:login", async (req, res) => {
  const knex = getKnex(req);

  try {
    const userService = new UserService(knex);
    const user = await userService.getUser(req.params.login);

    res.status(200).json(user);
  } catch (err) {
    res.status(400).send(`An error has occured: ${err}`);
  }
});

/** Deleting user */
router.delete("/:login", async (req, res) => {
  const knex = getKnex(req);

  try {
    const userService = new UserService(knex);
    await userService.delete(req.params.login);
    res.send(`User with ${req.params.login} was succesfully delted`);
  } catch (err) {
    res.send(`An error has occured: ${err}`);
  }
});

router.delete("/delete/all", async (req, res) => {
  const knex = getKnex(req);

  try {
    const userService = new UserService(knex);
    await userService.deleteAllUsers();
    res.send("All users have been succesfully deleted");
  } catch (err) {
    res.send(`An error has occured: ${err}`);
  }
});

router.post("/signin", async (req, res) => {
  const knex = getKnex(req);

  try {
    const userService = new UserService(knex);
    const user: User[] = await userService.verifyUser(req.body.login);

    if (user.length) {
      if (user[0].password === req.body.password) {
        res.status(200).json({ ok: true, data: omit(user[0], "password") });
      } else {
        res.status(400).json({ ok: false, message: "Bad password" });
      }
    } else {
      res.status(404).json({ ok: false, message: "User not found" });
    }
  } catch (err) {
    res.status(500).send(`An error has occured: ${err}`);
  }
});

export default router;
