import { logApiError } from "@/lib/api/security";
import { NextResponse } from "next/server";
import { uploadAttachmentBuffer } from "@/lib/attachments/server";
import { canManageWorkspace } from "@/lib/developers/auth";
import {
  downloadGmailAttachment,
  getGmailMessageDetail,
} from "@/lib/integrations/google-workspace";
import { createAdminClient } from "@/lib/supabase/admin";
import { createRouteClient } from "@/lib/supabase/route";
import type { GmailMessageSummary } from "@/types";

function createTextDocument(paragraphs: string[]) {
  const content = paragraphs
    .map((text) => text.trim())
    .filter(Boolean)
    .map((text) => ({
      type: "paragraph",
      content: [
        {
          type: "text",
          text,
        },
      ],
    }));

  return {
    type: "doc",
    content: content.length > 0 ? content : [{ type: "paragraph", content: [] }],
  };
}

export async function POST(
  req: Request,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const supabase = await createRouteClient();
    const {
      data: { user },
    } = await supabase.auth.getUser();
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

    const { id } = await context.params;
    const admin = createAdminClient();
    const { data: connection } = await admin
      .from("integration_connections")
      .select("id, team_id, provider, secret_encrypted")
      .eq("id", id)
      .eq("provider", "gmail")
      .maybeSingle();

    if (!connection) {
      return NextResponse.json({ error: "Gmail connection not found" }, { status: 404 });
    }

    const currentUser = user;
    const activeConnection = connection;

    const manageable = await canManageWorkspace(
      currentUser.id,
      activeConnection.team_id || null
    );
    if (!manageable) {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 });
    }

    const body = await req.json();
    const mode = body.mode === "task" ? "task" : "note";
    const message = body.message as GmailMessageSummary | undefined;

    if (!message?.id) {
      return NextResponse.json({ error: "A Gmail message is required" }, { status: 400 });
    }

    const detail = await getGmailMessageDetail(admin, activeConnection, message.id);
    const titleBase = detail.subject?.trim() || `Email from ${detail.from || "sender"}`;
    const openUrl = detail.webUrl || `https://mail.google.com/mail/u/0/#all/${detail.id}`;
    const detailLines = [
      `From: ${detail.from || "Unknown sender"}`,
      `Date: ${detail.date || detail.internalDate || "Unknown date"}`,
      `Gmail: ${openUrl}`,
      detail.attachmentNames.length > 0
        ? `Attachments: ${detail.attachmentNames.join(", ")}`
        : "",
      "",
      detail.textBody.trim() || "No message body available.",
    ];

    async function attachGmailFiles(entityType: "task" | "note", entityId: string) {
      for (const attachment of detail.attachments) {
        const file = await downloadGmailAttachment(admin, activeConnection, {
          messageId: detail.id,
          attachment,
        });

        await uploadAttachmentBuffer({
          userId: currentUser.id,
          teamId: activeConnection.team_id || null,
          projectId: null,
          entityType,
          entityId,
          fileName: file.fileName,
          mimeType: file.mimeType,
          buffer: file.buffer,
        });
      }
    }

    if (mode === "task") {
      const { data, error } = await admin
        .from("tasks")
        .insert({
          user_id: currentUser.id,
          team_id: activeConnection.team_id || null,
          title: `Follow up: ${titleBase}`,
          description: detailLines.join("\n"),
          status: "todo",
          priority: "none",
        })
        .select("id")
        .single();

      if (error) {
        return NextResponse.json({ error: error.message }, { status: 400 });
      }

      try {
        await attachGmailFiles("task", data.id);
      } catch (attachmentError) {
        await admin.from("tasks").delete().eq("id", data.id);
        throw attachmentError;
      }

      return NextResponse.json({
        success: true,
        entityType: "task",
        entityId: data.id,
        link: `/tasks?task=${data.id}`,
      });
    }

    const { data, error } = await admin
      .from("notes")
      .insert({
        user_id: currentUser.id,
        team_id: activeConnection.team_id || null,
        title: titleBase,
        content: createTextDocument(detailLines),
      })
      .select("id")
      .single();

    if (error) {
      return NextResponse.json({ error: error.message }, { status: 400 });
    }

    try {
      await attachGmailFiles("note", data.id);
    } catch (attachmentError) {
      await admin.from("notes").delete().eq("id", data.id);
      throw attachmentError;
    }

    return NextResponse.json({
      success: true,
      entityType: "note",
      entityId: data.id,
      link: `/notes/${data.id}`,
    });
  } catch (error) {
    logApiError("Gmail capture POST error:", error);
    return NextResponse.json({ error: "Failed to capture Gmail message" }, { status: 500 });
  }
}
