const express = require("express");
const app = express();
const path = require("path");
const cookie = require("cookie");
const cookieParser = require("cookie-parser");
const fs = require("fs");
const handlebars = require("handlebars");
const axios = require("axios");
const FormData = require("form-data");

require("dotenv").config();
app.use(express.static("static"));
app.use(cookieParser());

handlebars.registerHelper("eq", function (val1, val2, options) {
  return val1 === val2;
});

app.get("/logout", logout);

const twelveHoursInSeconds = 12 * 60 * 60; // 12 часов в секундах

const checkAuthorization = async (req, res, next) => {
  const token = req.cookies.token;

  console.log("checking token: " + token);

  if (!token) {
    res.redirect("/");
    return;
  }

  const options = {
    method: "GET",
    url: process.env.API_SERVER + "/secure",
    headers: {
      Authorization: token,
    },
  };

  try {
    const response = await axios.request(options);
    const authorizationHeader = response.headers["authorization"];

    const responseBody = response.data;
    req.apiResponse = responseBody;

    // Обновляем токен в cookies
    res.cookie("token", authorizationHeader, {
      maxAge: twelveHoursInSeconds * 1000,
    });

    next();
  } catch (error) {
    if (
      (error.response && error.response.status === 401) ||
      error.response.status === 400
    ) {
      res.redirect("/");
    } else {
      console.error("Ошибка при отправке GET-запроса:", error);
      res.status(500).send("Произошла ошибка при выполнении запроса.");
    }
  }
};

app.get("/", async (req, res) => {
  const token = req.cookies.token;

  var options = {
    method: "GET",
    url: process.env.API_SERVER + "/secure",
    headers: {
      Authorization: req.cookies.token,
    },
  };

  axios
    .request(options)
    .then(function (response) {
      const authorizationHeader = response.headers["authorization"];

      res.cookie("token", authorizationHeader, {
        maxAge: twelveHoursInSeconds * 1000,
      });

      console.log("redirecting to acc");

      res.redirect("/account");
    })
    .catch(function (error) {
      if (error.response && error.response.status === 401) {
        var templateData = {
          API_SERVER: process.env.API_SERVER,
        };

        const source = fs.readFileSync("static/templates/index.html", "utf8");
        const template = handlebars.compile(source);
        const resultT = template(templateData);
        res.send(resultT);
      } else if (error.response && error.response.status === 400) {
        var templateData = {
          API_SERVER: process.env.API_SERVER,
        };

        const source = fs.readFileSync("static/templates/setup.html", "utf8");
        const template = handlebars.compile(source);
        const resultT = template(templateData);
        res.send(resultT);
      } else {
        console.error("Ошибка при отправке GET-запроса:", error);
        res.status(500).send("Произошла ошибка при выполнении запроса.");
      }
    });
});

app.get("/signup", async (req, res) => {
  const token = req.cookies.token;

  var options = {
    method: "GET",
    url: process.env.API_SERVER + "/secure",
    headers: {
      Authorization: req.cookies.token,
    },
  };

  axios
    .request(options)
    .then(function (response) {
      const authorizationHeader = response.headers["authorization"];

      res.cookie("token", authorizationHeader, {
        maxAge: twelveHoursInSeconds * 1000,
      });
      res.redirect("/account");
    })
    .catch(function (error) {
      if (error.response) {
        var templateData = {
          API_SERVER: process.env.API_SERVER,
        };

        const source = fs.readFileSync("static/templates/signup.html", "utf8");
        const template = handlebars.compile(source);
        const resultT = template(templateData);
        res.send(resultT);
      } else {
        console.error("Ошибка при отправке GET-запроса:", error);
        res.status(500).send("Произошла ошибка при выполнении запроса.");
      }
    });
});

app.get("/signin", async (req, res) => {
  const token = req.cookies.token;

  var options = {
    method: "GET",
    url: process.env.API_SERVER + "/secure",
    headers: {
      Authorization: req.cookies.token,
    },
  };

  axios
    .request(options)
    .then(function (response) {
      const authorizationHeader = response.headers["authorization"];

      res.cookie("token", authorizationHeader, {
        maxAge: twelveHoursInSeconds * 1000,
      });
      res.redirect("/account");
    })
    .catch(function (error) {
      if (error.response) {
        var templateData = {
          API_SERVER: process.env.API_SERVER,
        };

        const source = fs.readFileSync("static/templates/signin.html", "utf8");
        const template = handlebars.compile(source);
        const resultT = template(templateData);
        res.send(resultT);
      } else {
        console.error("Ошибка при отправке GET-запроса:", error);
        res.status(500).send("Произошла ошибка при выполнении запроса.");
      }
    });
});

app.get("/account", checkAuthorization, async (req, res) => {
  const token = req.cookies.token;

  var options = {
    method: "GET",
    url: process.env.API_SERVER + "/account",
    headers: {
      Authorization: req.cookies.token,
    },
  };

  axios
    .request(options)
    .then(function (response) {
      const authorizationHeader = response.headers["authorization"];

      res.cookie("token", authorizationHeader, {
        maxAge: twelveHoursInSeconds * 1000,
      });

      var templateData = {
        API_SERVER: process.env.API_SERVER,
        Role: response.data.role,
        User: response.data.data,
      };

      const source = fs.readFileSync(
        "static/templates/account/account.html",
        "utf8"
      );
      const template = handlebars.compile(source);
      const resultT = template(templateData);
      res.send(resultT);
    })
    .catch(function (error) {
      if (error.response) {
        console.error("Ошибка при отправке GET-запроса:", error);
        res.status(500).send("Произошла ошибка при выполнении запроса.");
      }
    });
});

app.get("/account/settings", checkAuthorization, async (req, res) => {
  const token = req.cookies.token;

  var options = {
    method: "GET",
    url: process.env.API_SERVER + "/account",
    headers: {
      Authorization: req.cookies.token,
    },
  };

  axios
    .request(options)
    .then(function (response) {
      const authorizationHeader = response.headers["authorization"];

      res.cookie("token", authorizationHeader, {
        maxAge: twelveHoursInSeconds * 1000,
      });

      var templateData = {
        API_SERVER: process.env.API_SERVER,
        Role: response.data.role,
        User: response.data.data,
      };

      const source = fs.readFileSync(
        "static/templates/account/settings.html",
        "utf8"
      );
      const template = handlebars.compile(source);
      const resultT = template(templateData);
      res.send(resultT);
    })
    .catch(function (error) {
      if (error.response) {
        console.error("Ошибка при отправке GET-запроса:", error);
        res.status(500).send("Произошла ошибка при выполнении запроса.");
      }
    });
});

app.get("/account/newform", checkAuthorization, async (req, res) => {
  const token = req.cookies.token;

  var options = {
    method: "GET",
    url: process.env.API_SERVER + "/account",
    headers: {
      Authorization: req.cookies.token,
    },
  };

  axios
    .request(options)
    .then(function (response) {
      const authorizationHeader = response.headers["authorization"];

      res.cookie("token", authorizationHeader, {
        maxAge: twelveHoursInSeconds * 1000,
      });

      var templateData = {
        API_SERVER: process.env.API_SERVER,
        Role: response.data.role,
        User: response.data.data,
      };

      const source = fs.readFileSync(
        "static/templates/account/form.html",
        "utf8"
      );
      const template = handlebars.compile(source);
      const resultT = template(templateData);
      res.send(resultT);
    })
    .catch(function (error) {
      if (error.response) {
        console.error("Ошибка при отправке GET-запроса:", error);
        res.status(500).send("Произошла ошибка при выполнении запроса.");
      }
    });
});

app.get("/account/newtso", checkAuthorization, async (req, res) => {
  const token = req.cookies.token;

  var options = {
    method: "GET",
    url: process.env.API_SERVER + "/account",
    headers: {
      Authorization: req.cookies.token,
    },
  };

  axios
    .request(options)
    .then(function (response) {
      const authorizationHeader = response.headers["authorization"];

      res.cookie("token", authorizationHeader, {
        maxAge: twelveHoursInSeconds * 1000,
      });

      var templateData = {
        API_SERVER: process.env.API_SERVER,
        Role: response.data.role,
        User: response.data.data,
      };

      const source = fs.readFileSync(
        "static/templates/account/newtso.html",
        "utf8"
      );
      const template = handlebars.compile(source);
      const resultT = template(templateData);
      res.send(resultT);
    })
    .catch(function (error) {
      if (error.response) {
        console.error("Ошибка при отправке GET-запроса:", error);
        res.status(500).send("Произошла ошибка при выполнении запроса.");
      }
    });
});

app.get("/users", checkAuthorization, async (req, res) => {
  const token = req.cookies.token;

  var options = {
    method: "POST",
    url: process.env.API_SERVER + "/users/getusers",
    headers: {
      Authorization: req.cookies.token,
    },
  };

  axios
    .request(options)
    .then(function (response) {
      const authorizationHeader = response.headers["authorization"];

      res.cookie("token", authorizationHeader, {
        maxAge: twelveHoursInSeconds * 1000,
      });

      if (response.data.role !== "Дирекция") {
        if (response.data.role === "КПП") {
          var templateData = {
            API_SERVER: process.env.API_SERVER,
            User: response.data.userData,
            Role: response.data.role,
            People: response.data.people,
            Legals: response.data.legals,
            PeopleCount: response.data.totalCountPeople,
            LegalsCount: response.data.totalCountLegal,
          };

          const source = fs.readFileSync(
            "static/templates/account/readusers.html",
            "utf8"
          );
          const template = handlebars.compile(source);
          const resultT = template(templateData);
          res.send(resultT);
        } else {
          res.redirect("/account");
          return;
        }
      }

      var templateData = {
        API_SERVER: process.env.API_SERVER,
        User: response.data.userData,
        Role: response.data.role,
        People: response.data.people,
        Legals: response.data.legals,
        PeopleCount: response.data.totalCountPeople,
        LegalsCount: response.data.totalCountLegal,
      };

      const source = fs.readFileSync(
        "static/templates/account/users.html",
        "utf8"
      );
      const template = handlebars.compile(source);
      const resultT = template(templateData);
      res.send(resultT);
    })
    .catch(function (error) {
      if (error.response) {
        console.error("Ошибка при отправке GET-запроса:", error);
        res.status(500).send("Произошла ошибка при выполнении запроса.");
      }
    });
});

app.get("/applications", checkAuthorization, async (req, res) => {
  const token = req.cookies.token;

  var options = {
    method: "POST",
    url: process.env.API_SERVER + "/forms/getapplications",
    headers: {
      Authorization: req.cookies.token,
    },
  };

  axios
    .request(options)
    .then(function (response) {
      const authorizationHeader = response.headers["authorization"];

      res.cookie("token", authorizationHeader, {
        maxAge: twelveHoursInSeconds * 1000,
      });

      if (
        response.data.role !== "Дирекция" &&
        response.data.role !== "Пропуска"
      ) {
        res.redirect("/account");
        return;
      }

      var templateData = {
        API_SERVER: process.env.API_SERVER,
        User: response.data.userData,
        Role: response.data.role,
        Applications: response.data.applications,
        Total: response.data.totalCount,
      };

      const source = fs.readFileSync(
        "static/templates/account/applications.html",
        "utf8"
      );
      const template = handlebars.compile(source);
      const resultT = template(templateData);
      res.send(resultT);
    })
    .catch(function (error) {
      if (error.response) {
        console.error("Ошибка при отправке GET-запроса:", error);
        res.status(500).send("Произошла ошибка при выполнении запроса.");
      }
    });
});

app.get("/myapplications", checkAuthorization, async (req, res) => {
  const token = req.cookies.token;

  var options = {
    method: "POST",
    url: process.env.API_SERVER + "/forms/getmyapplications",
    headers: {
      Authorization: req.cookies.token,
    },
  };

  axios
    .request(options)
    .then(function (response) {
      const authorizationHeader = response.headers["authorization"];

      res.cookie("token", authorizationHeader, {
        maxAge: twelveHoursInSeconds * 1000,
      });

      var templateData = {
        API_SERVER: process.env.API_SERVER,
        User: response.data.userData,
        Role: response.data.role,
        Applications: response.data.applications,
        Total: response.data.totalCount,
      };

      const source = fs.readFileSync(
        "static/templates/account/myapplications.html",
        "utf8"
      );
      const template = handlebars.compile(source);
      const resultT = template(templateData);
      res.send(resultT);
    })
    .catch(function (error) {
      if (error.response) {
        console.error("Ошибка при отправке GET-запроса:", error);
        res.status(500).send("Произошла ошибка при выполнении запроса.");
      }
    });
});

app.get("/passes", checkAuthorization, async (req, res) => {
  const token = req.cookies.token;

  var options = {
    method: "POST",
    url: process.env.API_SERVER + "/passes/getpasses",
    headers: {
      Authorization: req.cookies.token,
    },
  };

  axios
    .request(options)
    .then(function (response) {
      const authorizationHeader = response.headers["authorization"];

      res.cookie("token", authorizationHeader, {
        maxAge: twelveHoursInSeconds * 1000,
      });

      if (
        response.data.role !== "Дирекция" &&
        response.data.role !== "Пропуска" &&
        response.data.role !== "КПП"
      ) {
        res.redirect("/account");
        return;
      }

      var templateData = {
        API_SERVER: process.env.API_SERVER,
        User: response.data.userData,
        Role: response.data.role,
        Passes: response.data.passes,
        Total: response.data.totalCount,
      };

      const source = fs.readFileSync(
        "static/templates/account/passes.html",
        "utf8"
      );
      const template = handlebars.compile(source);
      const resultT = template(templateData);
      res.send(resultT);
    })
    .catch(function (error) {
      if (error.response) {
        console.error("Ошибка при отправке GET-запроса:", error);
        res.status(500).send("Произошла ошибка при выполнении запроса.");
      }
    });
});

app.get("/tso", checkAuthorization, async (req, res) => {
  const token = req.cookies.token;

  var options = {
    method: "POST",
    url: process.env.API_SERVER + "/passes/gettso",
    headers: {
      Authorization: req.cookies.token,
    },
  };

  axios
    .request(options)
    .then(function (response) {
      const authorizationHeader = response.headers["authorization"];

      res.cookie("token", authorizationHeader, {
        maxAge: twelveHoursInSeconds * 1000,
      });

      if (
        response.data.role !== "Дирекция" &&
        response.data.role !== "Пропуска" &&
        response.data.role !== "КПП"
      ) {
        res.redirect("/account");
        return;
      }

      var templateData = {
        API_SERVER: process.env.API_SERVER,
        User: response.data.userData,
        Role: response.data.role,
        Passes: response.data.passes,
        Total: response.data.totalCount,
      };

      const source = fs.readFileSync(
        "static/templates/account/tso.html",
        "utf8"
      );
      const template = handlebars.compile(source);
      const resultT = template(templateData);
      res.send(resultT);
    })
    .catch(function (error) {
      if (error.response) {
        console.error("Ошибка при отправке GET-запроса:", error);
        res.status(500).send("Произошла ошибка при выполнении запроса.");
      }
    });
});

async function logout(req, res) {
  res.clearCookie("token");
  res.redirect("/login");
}

const port = 8081;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

app.use((req, res, next) => {
  res.redirect("/");
});
