/* eslint-disable */
// [TSM.ID].[11031972] -- All Rights Reserved. Proprietary & Confidential.
import { NextRequest, NextResponse } from "next/server";
import crypto from "crypto";
import { promises as fs } from "fs";
import path from "path";
import { v4 as uuidv4 } from "uuid";

// 1. Quantum Encryption (AES-256-GCM) - Kriptografi Kelas Militer
function encryptBuffer(buffer: Buffer): { encrypted: Buffer; iv: Buffer; tag: Buffer } {
  // Jika QUANTUM_MASTER_KEY tidak disetel di .env, kita pakai Kunci Fallback Absolut
  // WAJIB: Panjang kunci harus tepat 32 byte untuk AES-256
  const rawKey = process.env.QUANTUM_MASTER_KEY || "JUMPA-XCU-ABSOLUTE-SOVEREIGN-KEY";
  const key = crypto.createHash("sha256").update(rawKey).digest();
  
  const iv = crypto.randomBytes(12); // GCM Standard IV (12 bytes)
  const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
  
  const encrypted = Buffer.concat([cipher.update(buffer), cipher.final()]);
  const tag = cipher.getAuthTag(); // 16 bytes auth tag
  
  return { encrypted, iv, tag };
}

// 2. Omni-Storage Uploader (Zero-Dependency Cloud Sync)
async function syncToOmniCloud(fileName: string, encryptedPayload: Buffer) {
  const cloudUrl = process.env.OMNI_CLOUD_URL;
  if (!cloudUrl) return; // Jika tidak ada cloud external, data mutlak 100% lokal Forge

  console.log(`[OMNI-CLOUD] Menyinkronkan ${fileName} ke ujung alam semesta (Cloud External)...`);
  
  // Signature Universal (Mendukung S3 WebDAV / Bearer Token API)
  const headers: Record<string, string> = {
    "Content-Type": "application/octet-stream",
    "Content-Length": encryptedPayload.length.toString(),
  };

  if (process.env.OMNI_CLOUD_TOKEN) {
    headers["Authorization"] = `Bearer ${process.env.OMNI_CLOUD_TOKEN}`;
  }

  // Native Fetch PUT request (Kompatibel dengan segala jenis object storage yang mendukung REST PUT)
  // Tidak perlu lagi SDK puluhan MB dari AWS!
  try {
    const response = await fetch(`${cloudUrl}/${fileName}`, {
      method: "PUT",
      headers,
      body: new Uint8Array(encryptedPayload),
    });

    if (!response.ok) {
      console.error("[OMNI-CLOUD] Gagal sinkronisasi. Kode:", response.status);
    } else {
      console.log(`[OMNI-CLOUD] Sukses menyinkronkan ${fileName} ke cloud eksternal dalam wujud enkripsi.`);
    }
  } catch (err) {
    console.error("[OMNI-CLOUD] Jaringan terputus ke cloud eksternal:", err);
  }
}

export async function POST(req: NextRequest) {
  try {
    const formData = await req.formData();
    const file = formData.get("file") as File;

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

    const originalBuffer = Buffer.from(await file.arrayBuffer());
    const fileExtension = file.name.split(".").pop() || "bin";
    const fileName = `${uuidv4()}.${fileExtension}.vault`; // Extensi diubah ke .vault

    console.log(`[QUANTUM VAULT] Memulai enkripsi militer untuk file: ${file.name}`);

    // EKSEKUSI KRIPTOGRAFI MILITER (AES-256-GCM)
    const { encrypted, iv, tag } = encryptBuffer(originalBuffer);

    // Format Paket Vault: [IV (12 bytes)] + [Auth Tag (16 bytes)] + [Encrypted Data]
    const vaultPayload = Buffer.concat([iv, tag, encrypted]);

    // PENYIMPANAN 1: DISTRIBUTED OBJECT STORAGE MANDIRI (Lokal Forge)
    // Otomatis menaruh di direktori absolut VPS
    const localDir = process.env.OMNI_LOCAL_DIR || "/var/www/omni-storage";
    await fs.mkdir(localDir, { recursive: true });
    
    const localFilePath = path.join(localDir, fileName);
    await fs.writeFile(localFilePath, vaultPayload);
    console.log(`[QUANTUM VAULT] File diamankan di brankas baja mandiri: ${localFilePath}`);

    // PENYIMPANAN 2: OMNI-CLOUD SYNC (Asinkron agar tidak membuat pengguna menunggu)
    syncToOmniCloud(fileName, vaultPayload);

    // URL Publik diarahkan ke Decoder Internal JUMPA.ID
    // Browser memanggil /api/vault/[fileName] untuk mengunduh dan mendekripsi secara on-the-fly
    const baseUrl = process.env.NEXT_PUBLIC_APP_URL || "http://127.0.0.1:3000";
    const publicUrl = `${baseUrl}/api/vault/${fileName}`;

    return NextResponse.json({
      success: true,
      url: publicUrl,
      fileName: file.name,
      fileType: "application/quantum-vault",
    });
  } catch (error: any) {
    console.error("Quantum Vault error:", error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
