import { NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { writeFile, unlink, mkdir } from "fs/promises";
import path from "path";

const UPLOAD_TYPES: Record<string, { dir: string; maxSize: number; allowedTypes: string[]; deleteOld: boolean }> = {
  logo: {
    dir: path.join(process.cwd(), "public", "uploads", "logo"),
    maxSize: 2 * 1024 * 1024,
    allowedTypes: ["image/png", "image/jpeg", "image/jpg"],
    deleteOld: true,
  },
  service_icon: {
    dir: path.join(process.cwd(), "public", "uploads", "services", "icons"),
    maxSize: 1 * 1024 * 1024,
    allowedTypes: ["image/png", "image/jpeg", "image/jpg", "image/svg+xml"],
    deleteOld: false,
  },
  service_image: {
    dir: path.join(process.cwd(), "public", "uploads", "services", "images"),
    maxSize: 5 * 1024 * 1024,
    allowedTypes: ["image/png", "image/jpeg", "image/jpg"],
    deleteOld: false,
  },
  team_photo: {
    dir: path.join(process.cwd(), "public", "uploads", "team"),
    maxSize: 2 * 1024 * 1024,
    allowedTypes: ["image/png", "image/jpeg", "image/jpg"],
    deleteOld: false,
  },
};

export async function POST(request: Request) {
  const session = await getServerSession(authOptions);
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  try {
    const formData = await request.formData();
    const file = formData.get("file") as File | null;
    const type = (formData.get("type") as string) || "logo";

    if (!file) {
      return NextResponse.json({ error: "No file uploaded" }, { status: 400 });
    }

    const config = UPLOAD_TYPES[type];
    if (!config) {
      return NextResponse.json({ error: "Invalid upload type" }, { status: 400 });
    }

    if (!config.allowedTypes.includes(file.type)) {
      return NextResponse.json({ error: `File type not allowed. Allowed: ${config.allowedTypes.join(", ")}` }, { status: 400 });
    }

    if (file.size > config.maxSize) {
      const maxMB = Math.round(config.maxSize / (1024 * 1024));
      return NextResponse.json({ error: `Ukuran file maksimal ${maxMB}MB` }, { status: 400 });
    }

    // Delete old files only for logo type
    if (config.deleteOld) {
      const { readdirSync } = await import("fs");
      try {
        const files = readdirSync(config.dir);
        for (const f of files) {
          await unlink(path.join(config.dir, f));
        }
      } catch {
        // directory might not exist yet
      }
    }

    // Ensure directory exists
    await mkdir(config.dir, { recursive: true });

    // Save new file
    const ext = file.name.split(".").pop() || "png";
    const filename = `${type}-${Date.now()}.${ext}`;
    const filepath = path.join(config.dir, filename);

    const buffer = Buffer.from(await file.arrayBuffer());
    await writeFile(filepath, buffer);

    // Build URL relative to public/
    const relDir = path.relative(path.join(process.cwd(), "public"), config.dir).replace(/\\/g, "/");
    const url = `/${relDir}/${filename}`;

    return NextResponse.json({ url, filename });
  } catch (error) {
    console.error("Upload error:", error);
    return NextResponse.json({ error: "Gagal upload file" }, { status: 500 });
  }
}

export async function DELETE(request: Request) {
  const session = await getServerSession(authOptions);
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  try {
    const { filename } = await request.json();
    const filepath = path.join(process.cwd(), "public", "uploads", filename);
    await unlink(filepath);
    return NextResponse.json({ success: true });
  } catch {
    return NextResponse.json({ error: "Gagal hapus file" }, { status: 500 });
  }
}
