import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { ID, Permission, Role } from "node-appwrite";
import { InputFile } from "node-appwrite/file";

import { BUCKETS, DATABASE_ID, TABLES } from "@/lib/appwrite/schema";
import { createAdminClient } from "@/lib/appwrite/server";
import { requireTenant } from "@/lib/appwrite/tenant-guard";
import type { AttachmentItem } from "@/lib/appwrite/attachment-actions";

const MAX_BYTES = 20 * 1024 * 1024;

function teamFilePermissions(tenantId: string) {
  return [
    Permission.read(Role.team(tenantId)),
    Permission.delete(Role.team(tenantId, "owner")),
    Permission.delete(Role.team(tenantId, "admin")),
    Permission.delete(Role.team(tenantId, "member")),
  ];
}

export async function POST(request: NextRequest) {
  let ctx;
  try {
    ctx = await requireTenant();
  } catch {
    return NextResponse.json({ ok: false, error: "Unauthorized" }, { status: 401 });
  }

  let formData: FormData;
  try {
    formData = await request.formData();
  } catch {
    return NextResponse.json({ ok: false, error: "Invalid request" }, { status: 400 });
  }

  const entityType = String(formData.get("entityType") ?? "").trim();
  const entityId = String(formData.get("entityId") ?? "").trim();
  const file = formData.get("file");

  if (!entityType || !entityId) {
    return NextResponse.json({ ok: false, error: "Geçersiz istek." }, { status: 400 });
  }
  if (!(file instanceof File) || file.size === 0) {
    return NextResponse.json({ ok: false, error: "Dosya seçin." }, { status: 400 });
  }
  if (file.size > MAX_BYTES) {
    return NextResponse.json({ ok: false, error: "Dosya 20MB'dan büyük olamaz." }, { status: 400 });
  }

  const { storage, tablesDB } = createAdminClient();
  let createdFileId: string | null = null;

  try {
    const buffer = Buffer.from(await file.arrayBuffer());
    const inputFile = InputFile.fromBuffer(buffer, file.name);
    const perms = teamFilePermissions(ctx.tenantId);

    const created = await storage.createFile({
      bucketId: BUCKETS.entityAttachments,
      fileId: ID.unique(),
      file: inputFile,
      permissions: perms,
    });
    createdFileId = created.$id;

    const row = await tablesDB.createRow(
      DATABASE_ID,
      TABLES.attachments,
      ID.unique(),
      {
        tenantId: ctx.tenantId,
        createdBy: ctx.user.id,
        entityType,
        entityId,
        fileId: createdFileId,
        name: file.name,
        size: file.size,
        mimeType: file.type || null,
      },
      perms,
    );

    const attachment: AttachmentItem = {
      id: row.$id,
      fileId: createdFileId,
      name: file.name,
      size: file.size,
      mimeType: file.type ?? "",
      createdAt: row.$createdAt,
    };

    return NextResponse.json({ ok: true, attachment });
  } catch (e) {
    if (createdFileId) {
      try {
        await storage.deleteFile({ bucketId: BUCKETS.entityAttachments, fileId: createdFileId });
      } catch { /* best-effort cleanup */ }
    }
    return NextResponse.json(
      { ok: false, error: e instanceof Error ? e.message : "Yükleme başarısız." },
      { status: 500 },
    );
  }
}
