import "server-only";

import { env } from "@/lib/env";

export interface StorageDriver {
  /** Stores the file and returns its public URL (absolute, or root-relative for local storage). */
  put(key: string, body: Uint8Array, contentType: string): Promise<{ url: string }>;
  delete(key: string): Promise<void>;
}

let driver: Promise<StorageDriver> | undefined;

/**
 * The configured storage driver. `local` writes to disk and suits a single
 * long-running server; use `s3` (AWS S3, Cloudflare R2, DigitalOcean Spaces,
 * MinIO) on serverless hosts, whose file systems don't persist.
 */
export function storage() {
  driver ??=
    env().STORAGE_DRIVER === "s3"
      ? import("@/lib/storage/s3").then((mod) => mod.createS3Storage())
      : import("@/lib/storage/local").then((mod) => mod.createLocalStorage());
  return driver;
}

/** A collision-free storage key such as "2026/09/k3j9x2-airbnb-host.webp". */
export function buildStorageKey(originalName: string, extension: string) {
  const now = new Date();
  const base =
    originalName
      .replace(/\.[^.]+$/, "")
      .normalize("NFKD")
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, "-")
      .replace(/^-+|-+$/g, "")
      .slice(0, 60) || "image";
  const id = crypto.randomUUID().slice(0, 8);
  const month = String(now.getUTCMonth() + 1).padStart(2, "0");
  return `${now.getUTCFullYear()}/${month}/${id}-${base}.${extension}`;
}

/** Keys the app generates: lowercase path segments, no dot-segments. */
export const STORAGE_KEY_PATTERN =
  /^\d{4}\/\d{2}\/[a-z0-9-]+\.(?:jpg|png|webp|avif)$/;
