import { logApiError } from "@/lib/api/security";
import { NextResponse } from "next/server";
import { uploadAttachmentBuffer } from "@/lib/attachments/server";
import { canManageWorkspace } from "@/lib/developers/auth";
import { downloadGoogleDriveFile } from "@/lib/integrations/google-workspace";
import { createAdminClient } from "@/lib/supabase/admin";
import { createRouteClient } from "@/lib/supabase/route";
import type { GoogleDriveFileSummary } 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", "google_drive")
      .maybeSingle();

    if (!connection) {
      return NextResponse.json({ error: "Google Drive 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" ||
      body.mode === "note" ||
      body.mode === "existing_task" ||
      body.mode === "existing_note"
        ? body.mode
        : "note";
    const file = body.file as GoogleDriveFileSummary | undefined;

    if (!file?.id || !file.name) {
      return NextResponse.json({ error: "A Google Drive file is required" }, { status: 400 });
    }

    if (
      (mode === "existing_task" || mode === "existing_note") &&
      typeof body.targetEntityId !== "string"
    ) {
      return NextResponse.json({ error: "A target task or note is required." }, { status: 400 });
    }

    const openUrl = file.webViewLink || `https://drive.google.com/file/d/${file.id}/view`;
    const detailLines = [
      `Google Drive: ${openUrl}`,
      `Type: ${file.mimeType}`,
      file.modifiedTime ? `Modified: ${new Date(file.modifiedTime).toLocaleString()}` : "",
      file.owners.length > 0 ? `Owners: ${file.owners.join(", ")}` : "",
    ].filter(Boolean);

    const download = await downloadGoogleDriveFile(admin, activeConnection, file);

    async function attachToExistingTarget(
      entityType: "task" | "note",
      entityId: string
    ) {
      const table = entityType === "task" ? "tasks" : "notes";
      const { data: entity } = await admin
        .from(table)
        .select("id, user_id, team_id, project_id")
        .eq("id", entityId)
        .maybeSingle();

      if (!entity) {
        return NextResponse.json(
          { error: `Selected ${entityType} could not be found.` },
          { status: 404 }
        );
      }

      const sameWorkspace = activeConnection.team_id
        ? entity.team_id === activeConnection.team_id
        : !entity.team_id && entity.user_id === currentUser.id;

      if (!sameWorkspace) {
        return NextResponse.json(
          { error: `Selected ${entityType} is outside this workspace.` },
          { status: 403 }
        );
      }

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

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

    if (mode === "existing_task" && typeof body.targetEntityId === "string") {
      return await attachToExistingTarget("task", body.targetEntityId);
    }

    if (mode === "existing_note" && typeof body.targetEntityId === "string") {
      return await attachToExistingTarget("note", body.targetEntityId);
    }

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

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

      try {
        await uploadAttachmentBuffer({
          userId: currentUser.id,
          teamId: activeConnection.team_id || null,
          projectId: null,
          entityType: "task",
          entityId: data.id,
          fileName: download.fileName,
          mimeType: download.mimeType,
          buffer: download.buffer,
        });
      } 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: file.name,
        content: createTextDocument(detailLines),
      })
      .select("id")
      .single();

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

    try {
      await uploadAttachmentBuffer({
        userId: currentUser.id,
        teamId: activeConnection.team_id || null,
        projectId: null,
        entityType: "note",
        entityId: data.id,
        fileName: download.fileName,
        mimeType: download.mimeType,
        buffer: download.buffer,
      });
    } 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("Google Drive capture POST error:", error);
    return NextResponse.json({ error: "Failed to capture Google Drive file" }, { status: 500 });
  }
}
