import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

function escapeCsvField(field: string | null | undefined): string {
  if (field === null || field === undefined) return '""';
  const str = String(field);
  // Sanitize formula injection
  const sanitized = /^[=+\-@\t\r]/.test(str.trim()) ? `'${str.trim()}` : str;
  return `"${sanitized.replace(/"/g, '""')}"`;
}

function taskToVTodo(
  task: {
    id: string;
    title: string;
    note: string | null;
    completed: boolean;
    completedAt: Date | null;
    dueDate: Date | null;
    priority: number;
    createdAt: Date;
    updatedAt: Date;
    list?: { name: string } | null;
  }
) {
  const now = new Date().toISOString().replace(/[-:]/g, "").split(".")[0] + "Z";
  const priorityMap: Record<number, number> = { 0: 0, 1: 9, 2: 5, 3: 1 };
  const vtodo = [
    "BEGIN:VTODO",
    `UID:${task.id}@checkflow`,
    `DTSTAMP:${now}`,
    `CREATED:${task.createdAt.toISOString().replace(/[-:]/g, "").split(".")[0] + "Z"}`,
    `LAST-MODIFIED:${task.updatedAt.toISOString().replace(/[-:]/g, "").split(".")[0] + "Z"}`,
    `SUMMARY:${task.title.replace(/\n/g, "\\n")}`,
    `STATUS:${task.completed ? "COMPLETED" : "NEEDS-ACTION"}`,
    `PRIORITY:${priorityMap[task.priority] ?? 0}`,
  ];
  if (task.list?.name) {
    vtodo.push(`CATEGORIES:${task.list.name.replace(/\n/g, "\\n")}`);
  }
  if (task.note) {
    vtodo.push(`DESCRIPTION:${task.note.replace(/\n/g, "\\n")}`);
  }
  if (task.dueDate) {
    vtodo.push(`DUE:${task.dueDate.toISOString().replace(/[-:]/g, "").split(".")[0] + "Z"}`);
  }
  if (task.completedAt) {
    vtodo.push(`COMPLETED:${task.completedAt.toISOString().replace(/[-:]/g, "").split(".")[0] + "Z"}`);
  }
  vtodo.push("END:VTODO");
  return vtodo.join("\r\n");
}

export async function GET(req: NextRequest) {
  const session = await getServerSession(authOptions);
  if (!session?.user?.id) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { searchParams } = req.nextUrl;
  const format = (searchParams.get("format") || "csv").toLowerCase();
  const listId = searchParams.get("listId");
  const includeCompleted = searchParams.get("includeCompleted") !== "false";

  const whereClause: {
    userId: string;
    parentId: null;
    listId?: string;
    completed?: boolean;
  } = {
    userId: session.user.id,
    parentId: null,
  };

  if (listId && listId !== "all") {
    whereClause.listId = listId;
  }

  if (!includeCompleted) {
    whereClause.completed = false;
  }

  const tasks = await prisma.task.findMany({
    where: whereClause,
    include: {
      list: {
        select: { name: true },
      },
    },
    orderBy: [
      { listId: "asc" },
      { sortOrder: "asc" },
      { createdAt: "desc" },
    ],
  });

  const timestamp = new Date().toISOString().split("T")[0];

  if (format === "ics") {
    const icsContent = [
      "BEGIN:VCALENDAR",
      "VERSION:2.0",
      "PRODID:-//CheckFlow//CheckFlow Tasks Export//EN",
      "CALSCALE:GREGORIAN",
      "METHOD:PUBLISH",
      ...tasks.map(taskToVTodo),
      "END:VCALENDAR",
    ].join("\r\n");

    return new NextResponse(icsContent, {
      headers: {
        "Content-Type": "text/calendar; charset=utf-8",
        "Content-Disposition": `attachment; filename="checkflow-export-${timestamp}.ics"`,
        "Cache-Control": "no-cache, no-store, must-revalidate",
      },
    });
  }

  // Standard TickTick & RFC 4180 Compatible CSV
  const priorityLabels: Record<number, string> = { 0: "None", 1: "Low", 2: "Medium", 3: "High" };
  const headers = [
    "Folder Name",
    "List Name",
    "Title",
    "Tags",
    "Content",
    "Is Check list",
    "Start Date",
    "Due Date",
    "Reminder",
    "Repeat",
    "Priority",
    "Status",
    "Created Time",
    "Completed Time",
    "Order",
    "Timezone",
  ];

  const csvRows = [headers.map((h) => `"${h}"`).join(",")];

  for (let i = 0; i < tasks.length; i++) {
    const t = tasks[i];
    const row = [
      escapeCsvField(""), // Folder Name
      escapeCsvField(t.list?.name || "Inbox"), // List Name
      escapeCsvField(t.title), // Title
      escapeCsvField(""), // Tags
      escapeCsvField(t.note || ""), // Content / Note
      escapeCsvField("0"), // Is Check list
      escapeCsvField(""), // Start Date
      escapeCsvField(t.dueDate ? t.dueDate.toISOString() : ""), // Due Date
      escapeCsvField(""), // Reminder
      escapeCsvField(""), // Repeat
      escapeCsvField(priorityLabels[t.priority] || "None"), // Priority
      escapeCsvField(t.completed ? "Completed" : "Normal"), // Status
      escapeCsvField(t.createdAt.toISOString()), // Created Time
      escapeCsvField(t.completedAt ? t.completedAt.toISOString() : ""), // Completed Time
      escapeCsvField(String(t.sortOrder ?? i)), // Order
      escapeCsvField(Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"), // Timezone
    ];
    csvRows.push(row.join(","));
  }

  const csvContent = "\uFEFF" + csvRows.join("\r\n"); // UTF-8 BOM for Excel compatibility

  return new NextResponse(csvContent, {
    headers: {
      "Content-Type": "text/csv; charset=utf-8",
      "Content-Disposition": `attachment; filename="checkflow-export-${timestamp}.csv"`,
      "Cache-Control": "no-cache, no-store, must-revalidate",
    },
  });
}
