import "server-only";
import { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
import path from "node:path";
import {
  DeleteObjectCommand,
  GetObjectCommand,
  PutObjectCommand,
  S3Client,
} from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { env } from "@/lib/env";

/**
 * File storage abstraction.
 *
 * Two drivers:
 *   • `local` — writes under `.data/uploads` (development default, no services)
 *   • `s3`    — S3-compatible object storage (MinIO / R2 / AWS S3 / Wasabi)
 *
 * Callers only ever see `{ key, url }`, so switching drivers never touches
 * feature code.
 */

export interface StoredFile {
  key: string;
  url: string;
  size: number;
  contentType: string;
  originalName: string;
}

export interface UploadInput {
  file: File;
  /** Logical folder, e.g. `submissions` or `avatars`. */
  folder: string;
}

export class StorageError extends Error {
  constructor(message: string) {
    super(message);
    this.name = "StorageError";
  }
}

/** Static extension allow-list: extension → allowed. */
const ALLOWED_EXTENSIONS: Record<string, true> = {
  ".pdf": true,
  ".doc": true,
  ".docx": true,
  ".ppt": true,
  ".pptx": true,
  ".xls": true,
  ".xlsx": true,
  ".txt": true,
  ".md": true,
  ".csv": true,
  ".json": true,
  ".zip": true,
  ".png": true,
  ".jpg": true,
  ".jpeg": true,
  ".gif": true,
  ".webp": true,
  ".svg": true,
  ".js": true,
  ".ts": true,
  ".py": true,
  ".ino": true,
  ".c": true,
  ".cpp": true,
  ".h": true,
  ".java": true,
  ".rb": true,
};

/** Executable/script formats that must never be accepted as uploads. */
const BLOCKED_EXTENSIONS: Record<string, true> = {
  ".exe": true,
  ".bat": true,
  ".cmd": true,
  ".com": true,
  ".msi": true,
  ".scr": true,
  ".ps1": true,
  ".sh": true,
  ".dll": true,
  ".so": true,
  ".dylib": true,
  ".jar": true,
  ".app": true,
  ".vbs": true,
};

function sanitiseFileName(name: string): string {
  const base = path.basename(name).replace(/[^\w.\-() ]+/g, "_");
  return base.slice(0, 180) || "upload";
}

function extensionOf(name: string): string {
  const index = name.lastIndexOf(".");
  return index === -1 ? "" : name.slice(index).toLowerCase();
}

function assertUploadAllowed(file: File) {
  if (file.size === 0) throw new StorageError("The uploaded file is empty.");
  if (file.size > env.maxUploadBytes) {
    throw new StorageError(
      `File is too large. Maximum size is ${env.STORAGE_MAX_UPLOAD_MB} MB.`
    );
  }
  const ext = extensionOf(file.name);
  if (BLOCKED_EXTENSIONS[ext]) {
    throw new StorageError(`Files of type "${ext}" are not permitted.`);
  }
  if (ext && !ALLOWED_EXTENSIONS[ext]) {
    throw new StorageError(`Unsupported file type "${ext}".`);
  }
}

/** Build a collision-resistant, path-traversal-safe object key. */
function buildKey(folder: string, originalName: string): string {
  const safeFolder = folder.replace(/[^a-z0-9/_-]/gi, "").replace(/^\/+|\/+$/g, "") || "misc";
  const stamp = new Date().toISOString().slice(0, 10);
  const id = randomUUID();
  return `${safeFolder}/${stamp}/${id}-${sanitiseFileName(originalName)}`;
}

// --- local driver -----------------------------------------------------------

function localRoot(): string {
  // The root is runtime configuration (env-driven), so static analysis cannot
  // scope it. Without this hint Turbopack traces the entire project into the
  // server bundle, which is both wasteful and wrong here.
  return path.resolve(/* turbopackIgnore: true */ process.cwd(), env.STORAGE_LOCAL_DIR);
}

/** Resolve a key inside the upload root, rejecting traversal attempts. */
function resolveWithinRoot(key: string): string | null {
  const root = localRoot();
  const target = path.resolve(/* turbopackIgnore: true */ root, key);
  return target.startsWith(root + path.sep) ? target : null;
}

async function saveLocal(key: string, file: File): Promise<StoredFile> {
  const target = resolveWithinRoot(key);
  if (!target) throw new StorageError("Resolved upload path escaped the storage root.");
  await fs.mkdir(path.dirname(target), { recursive: true });
  const bytes = Buffer.from(await file.arrayBuffer());
  await fs.writeFile(target, bytes);
  return {
    key,
    // The trailing `/download` keeps the request out of the host's
    // extension-based 404 filter; see the file route and `fileHref`.
    url: `/api/files/${key}/download`,
    size: bytes.byteLength,
    contentType: file.type || "application/octet-stream",
    originalName: file.name,
  };
}

// --- s3 driver --------------------------------------------------------------

let cachedS3: S3Client | null = null;

function s3Client(): S3Client {
  if (cachedS3) return cachedS3;
  if (!env.STORAGE_S3_BUCKET) throw new StorageError("STORAGE_S3_BUCKET is not configured.");
  cachedS3 = new S3Client({
    region: env.STORAGE_S3_REGION,
    endpoint: env.STORAGE_S3_ENDPOINT || undefined,
    forcePathStyle: env.STORAGE_S3_FORCE_PATH_STYLE,
    credentials: env.STORAGE_S3_ACCESS_KEY_ID
      ? {
          accessKeyId: env.STORAGE_S3_ACCESS_KEY_ID,
          secretAccessKey: env.STORAGE_S3_SECRET_ACCESS_KEY ?? "",
        }
      : undefined,
  });
  return cachedS3;
}

async function saveS3(key: string, file: File): Promise<StoredFile> {
  const client = s3Client();
  const bytes = Buffer.from(await file.arrayBuffer());
  const contentType = file.type || "application/octet-stream";

  await client.send(
    new PutObjectCommand({
      Bucket: env.STORAGE_S3_BUCKET,
      Key: key,
      Body: bytes,
      ContentType: contentType,
    })
  );

  const publicBase = env.STORAGE_S3_PUBLIC_BASE_URL?.replace(/\/+$/, "");
  const url = publicBase
    ? `${publicBase}/${key}`
    : await getSignedUrl(
        client,
        new GetObjectCommand({ Bucket: env.STORAGE_S3_BUCKET, Key: key }),
        { expiresIn: 60 * 60 * 24 * 7 }
      );

  return { key, url, size: bytes.byteLength, contentType, originalName: file.name };
}

// --- public API -------------------------------------------------------------

export async function uploadFile({ file, folder }: UploadInput): Promise<StoredFile> {
  assertUploadAllowed(file);
  const key = buildKey(folder, file.name);
  return env.STORAGE_DRIVER === "s3" ? saveS3(key, file) : saveLocal(key, file);
}

export async function readLocalFile(key: string): Promise<Buffer | null> {
  const target = resolveWithinRoot(key);
  if (!target) return null;
  try {
    return await fs.readFile(target);
  } catch {
    return null;
  }
}

export async function deleteFile(key: string): Promise<void> {
  if (env.STORAGE_DRIVER === "s3") {
    await s3Client()
      .send(new DeleteObjectCommand({ Bucket: env.STORAGE_S3_BUCKET, Key: key }))
      .catch(() => {});
    return;
  }
  const target = resolveWithinRoot(key);
  if (!target) return;
  await fs.rm(target, { force: true }).catch(() => {});
}

export const storageInfo = {
  driver: env.STORAGE_DRIVER,
  maxUploadMb: env.STORAGE_MAX_UPLOAD_MB,
  acceptedExtensions: Object.keys(ALLOWED_EXTENSIONS).sort(),
};
