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 } from "@/lib/appwrite/schema";
import { createAdminClient } from "@/lib/appwrite/server";
import { requireTenant } from "@/lib/appwrite/tenant-guard";

const MAX_BYTES = 20 * 1024 * 1024;

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

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

  const file = formData.get("file");
  if (!(file instanceof File) || file.size === 0) {
    return NextResponse.json({ ok: false, error: "Dosya seçin." }, { status: 400 });
  }
  if (!file.type.startsWith("image/")) {
    return NextResponse.json({ ok: false, error: "Sadece görsel dosyaları desteklenir." }, { status: 400 });
  }
  if (file.size > MAX_BYTES) {
    return NextResponse.json({ ok: false, error: "Dosya 20 MB'dan büyük olamaz." }, { status: 400 });
  }

  const { storage } = createAdminClient();

  try {
    const buffer = Buffer.from(await file.arrayBuffer());
    const extMap: Record<string, string> = {
      "image/jpeg": ".jpg",
      "image/png": ".png",
      "image/webp": ".webp",
      "image/gif": ".gif",
      "image/avif": ".avif",
    };
    const ext = extMap[file.type] ?? ".jpg";
    const baseName = file.name.replace(/\.[^/.]+$/, "");
    const safeName = baseName + ext;
    const inputFile = InputFile.fromBuffer(buffer, safeName);

    const created = await storage.createFile(
      BUCKETS.propertyImages,
      ID.unique(),
      inputFile,
      [
        Permission.read(Role.any()),
        Permission.update(Role.team(ctx.tenantId)),
        Permission.delete(Role.team(ctx.tenantId, "owner")),
        Permission.delete(Role.team(ctx.tenantId, "admin")),
      ],
    );

    return NextResponse.json({ ok: true, fileId: created.$id });
  } catch (e) {
    const msg = e instanceof Error ? e.message : String(e);
    console.error("Property image upload error:", e);
    return NextResponse.json(
      { ok: false, error: process.env.NODE_ENV === "development" ? msg : "Fotoğraf yüklenemedi." },
      { status: 500 },
    );
  }
}
