const router = require("express").Router();

router.get("/users", (request, response) => {
  response.send(require("./json/users/users.json"));
});

router.post("/auth", (request, response) => {
  const { phoneNumber, password } = request.body;
  console.log(phoneNumber, password);
  if (phoneNumber === "89999999999" || phoneNumber === "89559999999") {
    response.send(require("./json/auth/success.json"));
  } else {
    response.status(401).send(require("./json/auth/error.json"));
  }
});

router.post("/auth/2fa", (request, response) => {
  const { phoneNumber, code } = request.body;
  if (code === "0000" && phoneNumber === "89999999999") {
    response.send(require("./json/2fa/dogsitter.success.json"));
  } else if (code === "0000" && phoneNumber === "89559999999") {
    response.send(require("./json/2fa/owner.success.json"));
  } else {
    response.status(401).send(require("./json/2fa/error.json"));
  }
});

router.post("/register", (request, response) => {
  const { firstName, secondName, phoneNumber, password, role } = request.body;
  console.log(phoneNumber, password, role);
  if (phoneNumber === "89999999999" || phoneNumber === "89559999999") {
    response.status(401).send(require("./json/register/error.json"));
  } else if (role === "dogsitter") {
    response.send(require("./json/register/dogsitter.success.json"));
  } else {
    response.send(require("./json/register/owner.success.json"));
  }
});

router.get("/auth/session", (request, response) => {
  const authHeader = request.headers.authorization;

  if (!authHeader) {
    return response.status(401).json({ error: "Authorization header missing" });
  }

  // Берём сам токен из заголовка
  const token = authHeader.split(" ")[1];

  if (!token) {
    return response.status(401).json({ error: "Bearer token missing" });
  }

  const jwt = require("jsonwebtoken");
  const secretKey = "secret";

  try {
    const decoded = jwt.verify(token, secretKey);

    if (decoded.role === "dogsitter") {
      response.send(require("./json/role/dogsitter.success.json"));
    } else {
      response.send(require("./json/role/owner.success.json"));
    }
  } catch (e) {
    console.log("token e:", e);
    return response.status(403).json({ error: "Invalid token" });
  }
});


// Проверка взаимодействия между пользователем и догситтером
router.get("/interactions/check", (req, res) => {
  const { owner_id, dogsitter_id } = req.query;

  const usersFilePath = path.resolve(__dirname, "./json/users/users.json");

  delete require.cache[require.resolve(usersFilePath)];
  const usersFile = require(usersFilePath);

  const interactions = usersFile.interactions || [];

  const exists = interactions.some(
    (interaction) =>
      interaction.owner_id === Number(owner_id) &&
      interaction.dogsitter_id === Number(dogsitter_id)
  );

  res.json({ exists });
});

// Добавление нового взаимодействия
router.post("/interactions", (req, res) => {
  const { owner_id, dogsitter_id, interaction_type } = req.body;

  if (!owner_id || !dogsitter_id || !interaction_type) {
    return res.status(400).json({ error: "Missing required fields" });
  }

  const usersFilePath = path.resolve(__dirname, "./json/users/users.json");

  delete require.cache[require.resolve(usersFilePath)];
  const usersFile = require(usersFilePath);

  if (!usersFile.interactions) {
    usersFile.interactions = [];
  }

  // Проверяем, существует ли уже такое взаимодействие
  const exists = usersFile.interactions.some(
    (interaction) =>
      interaction.owner_id === Number(owner_id) &&
      interaction.dogsitter_id === Number(dogsitter_id)
  );

  if (!exists) {
    usersFile.interactions.push({
      owner_id: Number(owner_id),
      dogsitter_id: Number(dogsitter_id),
      interaction_type,
    });

    fs.writeFileSync(
      usersFilePath,
      JSON.stringify(usersFile, null, 2),
      "utf8"
    );

    console.log(
      `Добавлено взаимодействие: owner_id=${owner_id}, dogsitter_id=${dogsitter_id}`
    );
  }

  res.json({ success: true });
});

router.get("/dogsitter-viewing", (req, res) => {
  const { id } = req.query;
  console.log(`Получен запрос для dogsitter с ID: ${id}`);

  const usersFile = require("./json/users/users.json");
  const users = usersFile.data; // Извлекаем массив из свойства "data"

  const user = users.find((user) => user.id === Number(id));

  if (user) {
    res.json(user); // Возвращаем найденного пользователя
  } else {
    res.status(404).json({ error: "User not found" }); // Если пользователь не найден
  }
});

const fs = require('fs');
const path = require('path');


router.post('/dogsitter-viewing/rating/:id', (req, res) => {
  const { id } = req.params;
  const { rating } = req.body;

  if (!rating || rating < 1 || rating > 5) {
    return res.status(400).json({ error: 'Некорректная оценка' });
  }

  const usersFilePath = path.resolve(__dirname, "./json/users/users.json");

  delete require.cache[require.resolve(usersFilePath)];
  const usersFile = require(usersFilePath);
  const users = usersFile.data;

  const userIndex = users.findIndex(user => user.id === Number(id));
  if (userIndex === -1) {
    return res.status(404).json({ error: 'Догситтер не найден' });
  }

  if (!users[userIndex].ratings) {
    users[userIndex].ratings = [];
  }
  users[userIndex].ratings.push(rating);

  if (users[userIndex].ratings.length > 100) {
    users[userIndex].ratings.shift();
  }

  const total = users[userIndex].ratings.reduce((sum, r) => sum + r, 0);
  users[userIndex].rating = parseFloat((total / users[userIndex].ratings.length).toFixed(2));

  fs.writeFileSync(usersFilePath, JSON.stringify({ data: users }, null, 2), 'utf8');

  console.log(`Обновлен рейтинг догситтера ${id}: ${users[userIndex].rating}`);

  res.json({ rating: users[userIndex].rating, ratings: users[userIndex].ratings });
});


router.patch('/users/:id', (req, res) => {
  const { id } = req.params;
  const updateData = req.body;

  console.log('Полученные данные для обновления:', updateData);


  const usersFilePath = path.resolve(__dirname, "./json/users/users.json");

  delete require.cache[require.resolve(usersFilePath)];
  const usersFile = require(usersFilePath);
  const users = usersFile.data;

  const userIndex = users.findIndex((user) => user.id === Number(id));
  if (userIndex === -1) {
    return res.status(404).json({ error: 'User not found' });
  }

  users[userIndex] = { ...users[userIndex], ...updateData };

  fs.writeFileSync(
    usersFilePath,
    JSON.stringify({ data: users }, null, 2),
    'utf8'
  );

  console.log('Обновлённые данные пользователя:', users[userIndex]);

  res.json(users[userIndex]);
});


module.exports = router