import type { APIRoute } from "astro";

const POCKETBASE_URL = import.meta.env.POCKETBASE_URL || "http://localhost:8090";

// Валидация PocketBase ID (15 символов, lowercase alphanumeric)
const POCKETBASE_ID_REGEX = /^[a-z0-9]{15}$/;

// GET - получить количество лайков/дизлайков и голос пользователя
export const GET: APIRoute = async ({ url, cookies }) => {
  const postId = url.searchParams.get("post_id");
  const token = cookies.get("pb_auth")?.value?.trim();

  if (!postId) {
    return new Response(
      JSON.stringify({ error: "post_id required" }),
      { status: 400, headers: { "Content-Type": "application/json" } }
    );
  }

  // Валидация формата ID
  if (!POCKETBASE_ID_REGEX.test(postId)) {
    return new Response(
      JSON.stringify({ error: "Неверный формат post_id" }),
      { status: 400, headers: { "Content-Type": "application/json" } }
    );
  }

  try {
    // Получаем пост из PocketBase
    const postResponse = await fetch(
      `${POCKETBASE_URL}/api/collections/posts/records/${postId}`,
      {
        headers: token ? { Authorization: `Bearer ${token}` } : {},
      }
    );

    if (!postResponse.ok) {
      return new Response(
        JSON.stringify({ error: "Post not found" }),
        { status: 404, headers: { "Content-Type": "application/json" } }
      );
    }

    const post = await postResponse.json();

    // Если пользователь авторизован, проверяем его голос
    let userVote: "like" | "dislike" | null = null;
    if (token) {
      try {
        const userResponse = await fetch(
          `${POCKETBASE_URL}/api/collections/users/auth-refresh`,
          {
            method: "POST",
            headers: {
              Authorization: `Bearer ${token}`,
              "Content-Type": "application/json",
            },
          }
        );

        if (userResponse.ok) {
          const userData = await userResponse.json();
          const userId = userData.record?.id;

          const voteResponse = await fetch(
            `${POCKETBASE_URL}/api/collections/post_votes/records?filter=post="${postId}"&&user="${userId}"`,
            {
              headers: { Authorization: `Bearer ${token}` },
            }
          );
          if (voteResponse.ok) {
            const voteData = await voteResponse.json();
            if (voteData.items?.length > 0) {
              userVote = voteData.items[0].vote_type;
            }
          }
        }
      } catch (e) {
        console.error("[Likes API] Ошибка проверки голоса:", e);
      }
    }

    return new Response(
      JSON.stringify({
        likes: post.likes || 0,
        dislikes: post.dislikes || 0,
        userVote,
      }),
      { status: 200, headers: { "Content-Type": "application/json" } }
    );
  } catch (error) {
    console.error("[Likes API GET] Error:", error);
    return new Response(
      JSON.stringify({ error: "Failed to fetch likes" }),
      { status: 500, headers: { "Content-Type": "application/json" } }
    );
  }
};

// POST - поставить лайк/дизлайк
export const POST: APIRoute = async ({ request, cookies }) => {
  const token = cookies.get("pb_auth")?.value?.trim();

  if (!token) {
    return new Response(
      JSON.stringify({ error: "Требуется авторизация" }),
      { status: 401, headers: { "Content-Type": "application/json" } }
    );
  }

  try {
    // Получаем данные пользователя из токена
    const userResponse = await fetch(
      `${POCKETBASE_URL}/api/collections/users/auth-refresh`,
      {
        method: "POST",
        headers: {
          Authorization: `Bearer ${token}`,
          "Content-Type": "application/json",
        },
      }
    );

    if (!userResponse.ok) {
      return new Response(
        JSON.stringify({ error: "Неверный токен" }),
        { status: 401, headers: { "Content-Type": "application/json" } }
      );
    }

    const userData = await userResponse.json();
    const userId = userData.record?.id;

    const body = await request.json();
    const { post_id, vote_type } = body;

    // Валидация post_id
    if (!post_id || !POCKETBASE_ID_REGEX.test(post_id)) {
      return new Response(
        JSON.stringify({ error: "Неверный формат post_id" }),
        { status: 400, headers: { "Content-Type": "application/json" } }
      );
    }

    // Валидация vote_type
    if (!vote_type || !["like", "dislike"].includes(vote_type)) {
      return new Response(
        JSON.stringify({ error: "Некорректный vote_type" }),
        { status: 400, headers: { "Content-Type": "application/json" } }
      );
    }

    // Проверяем существующий голос
    const existingVoteResponse = await fetch(
      `${POCKETBASE_URL}/api/collections/post_votes/records?filter=post="${post_id}"&&user="${userId}"`,
      {
        headers: { Authorization: `Bearer ${token}` },
      }
    );

    let currentLikes = 0;
    let currentDislikes = 0;

    // Получаем текущие счётчики
    const postResponse = await fetch(
      `${POCKETBASE_URL}/api/collections/posts/records/${post_id}`,
      {
        headers: { Authorization: `Bearer ${token}` },
      }
    );
    if (postResponse.ok) {
      const post = await postResponse.json();
      currentLikes = post.likes || 0;
      currentDislikes = post.dislikes || 0;
    }

    if (existingVoteResponse.ok) {
      const existingVote = await existingVoteResponse.json();

      if (existingVote.items?.length > 0) {
        const existingVoteId = existingVote.items[0].id;
        const existingVoteType = existingVote.items[0].vote_type;

        // Если голос совпадает - удаляем (отмена голоса)
        if (existingVoteType === vote_type) {
          await fetch(
            `${POCKETBASE_URL}/api/collections/post_votes/records/${existingVoteId}`,
            {
              method: "DELETE",
              headers: { Authorization: `Bearer ${token}` },
            }
          );

          // Уменьшаем счётчик
          if (vote_type === "like") {
            currentLikes = Math.max(0, currentLikes - 1);
          } else {
            currentDislikes = Math.max(0, currentDislikes - 1);
          }
        } else {
          // Если голос отличается - обновляем
          await fetch(
            `${POCKETBASE_URL}/api/collections/post_votes/records/${existingVoteId}`,
            {
              method: "PATCH",
              headers: {
                Authorization: `Bearer ${token}`,
                "Content-Type": "application/json",
              },
              body: JSON.stringify({ vote_type }),
            }
          );

          // Корректируем счётчики
          if (existingVoteType === "like" && vote_type === "dislike") {
            currentLikes = Math.max(0, currentLikes - 1);
            currentDislikes++;
          } else if (existingVoteType === "dislike" && vote_type === "like") {
            currentDislikes = Math.max(0, currentDislikes - 1);
            currentLikes++;
          }
        }
      } else {
        // Новый голос
        await fetch(
          `${POCKETBASE_URL}/api/collections/post_votes/records`,
          {
            method: "POST",
            headers: {
              Authorization: `Bearer ${token}`,
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              post: post_id,
              user: userId,
              vote_type,
            }),
          }
        );

        if (vote_type === "like") {
          currentLikes++;
        } else {
          currentDislikes++;
        }
      }
    } else {
      // Новый голос
      await fetch(
        `${POCKETBASE_URL}/api/collections/post_votes/records`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${token}`,
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            post: post_id,
            user: userId,
            vote_type,
          }),
        }
      );

      if (vote_type === "like") {
        currentLikes++;
      } else {
        currentDislikes++;
      }
    }

    // Обновляем счётчики в посте
    await fetch(
      `${POCKETBASE_URL}/api/collections/posts/records/${post_id}`,
      {
        method: "PATCH",
        headers: {
          Authorization: `Bearer ${token}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          likes: currentLikes,
          dislikes: currentDislikes,
        }),
      }
    );

    return new Response(
      JSON.stringify({
        likes: currentLikes,
        dislikes: currentDislikes,
        userVote: vote_type,
      }),
      { status: 200, headers: { "Content-Type": "application/json" } }
    );
  } catch (error) {
    console.error("[Likes API POST] Error:", error);
    return new Response(
      JSON.stringify({ error: "Не удалось сохранить голос" }),
      { status: 500, headers: { "Content-Type": "application/json" } }
    );
  }
};
