import type { APIRoute } from "astro";
import { sendEmail } from "../../../lib/email";

const POCKETBASE_URL = import.meta.env.POCKETBASE_URL || "http://localhost:8090";
const ADMIN_EMAIL = import.meta.env.PB_ADMIN_EMAIL || "redibedi2019@gmail.com";

export const POST: APIRoute = async ({ request, cookies }) => {
  const pbAuthCookie = cookies.get("pb_auth")?.value;
  const token = pbAuthCookie?.trim();

  if (!token) {
    return new Response(
      JSON.stringify({ error: "Unauthorized" }),
      { status: 401, headers: { "Content-Type": "application/json" } }
    );
  }

  try {
    let userId: string | null = null;
    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();
      userId = userData.record?.id;
    }

    if (!userId) {
      return new Response(
        JSON.stringify({ error: "Unauthorized" }),
        { status: 401, headers: { "Content-Type": "application/json" } }
      );
    }

    const body = await request.json();
    const { name, surname, profession, rating, text } = body;

    if (!name || !surname || !profession || !rating || !text) {
      return new Response(
        JSON.stringify({ error: "Все поля обязательны" }),
        { status: 400, headers: { "Content-Type": "application/json" } }
      );
    }

    if (text.length < 50 || text.length > 2000) {
      return new Response(
        JSON.stringify({ error: "Текст отзыва должен быть от 50 до 2000 символов" }),
        { status: 400, headers: { "Content-Type": "application/json" } }
      );
    }

    if (rating < 1 || rating > 5) {
      return new Response(
        JSON.stringify({ error: "Оценка должна быть от 1 до 5" }),
        { status: 400, headers: { "Content-Type": "application/json" } }
      );
    }

    const response = await fetch(
      `${POCKETBASE_URL}/api/collections/reviews/records`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({
          name,
          surname,
          profession,
          rating,
          text,
          status: "published",
          votesCount: 0,
          user: userId,
        }),
      }
    );

    const data = await response.json();

    if (!response.ok) {
      return new Response(JSON.stringify(data), {
        status: response.status,
        headers: { "Content-Type": "application/json" },
      });
    }

    try {
      await sendEmail({
        to: ADMIN_EMAIL,
        subject: `Новый отзыв на сайте: ${rating} звёзд от ${name} ${surname}`,
        html: `
          <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
            <h2 style="color: #1e3050;">Новый отзыв на сайте</h2>
            <div style="background: #f8fafc; padding: 20px; border-radius: 12px; margin: 20px 0;">
              <p><strong>Автор:</strong> ${name} ${surname}</p>
              <p><strong>Профессия:</strong> ${profession}</p>
              <p><strong>Оценка:</strong> ${"⭐".repeat(rating)} (${rating}/5)</p>
              <p><strong>Дата:</strong> ${new Date().toLocaleDateString("ru-RU")}</p>
            </div>
            <div style="background: #ffffff; padding: 20px; border: 1px solid #e2e8f0; border-radius: 12px;">
              <p style="margin: 0; line-height: 1.6;">${text}</p>
            </div>
            <p style="color: #64748b; font-size: 14px; margin-top: 20px;">
              Это письмо отправлено автоматически с сайта avtourist-surgut.ru
            </p>
          </div>
        `,
      });
    } catch (emailError) {
      console.error("[Reviews API] Email error:", emailError);
    }

    return new Response(JSON.stringify(data), {
      status: 201,
      headers: { "Content-Type": "application/json" },
    });
  } catch (error) {
    console.error("[Reviews API POST] Error:", error);
    return new Response(
      JSON.stringify({ error: "Failed to create review" }),
      { status: 500, headers: { "Content-Type": "application/json" } }
    );
  }
};

export const GET: APIRoute = async ({ url }) => {
  const status = url.searchParams.get("status") || "published";
  const expand = "user";
  const sort = "-created";

  let filter = `status = "${status}"`;
  
  try {
    const response = await fetch(
      `${POCKETBASE_URL}/api/collections/reviews/records?expand=${expand}&filter=${encodeURIComponent(filter)}&sort=${sort}`,
      {}
    );

    const data = await response.json();
    return new Response(JSON.stringify(data), {
      status: 200,
      headers: { "Content-Type": "application/json" },
    });
  } catch (error) {
    console.error("[Reviews API GET] Error:", error);
    return new Response(
      JSON.stringify({ error: "Failed to fetch reviews" }),
      { status: 500, headers: { "Content-Type": "application/json" } }
    );
  }
};