import { randomUUID } from "node:crypto";
import { unlink, writeFile } from "node:fs/promises";
import { join } from "node:path";

/**
 *
 */
export class LocalFileRepository {
  constructor(private readonly uploadDirectory: string) {}

  private log(message: string): void {
    console.log(`[LocalFileRepository] ${message}`);
  }
  async saveFile(file: File): Promise<{
    fileName: string;
    filePath: string;
  }> {
    this.log(
      `Saving file: ${file.name} (size: ${file.size} bytes, type: ${file.type})`,
    );
    const filetype = file.type.split("/")[1];
    const fileName = `${randomUUID()}.${filetype}`;
    const filePath = join(this.uploadDirectory, fileName);

    const fileContentBuffer = await file.arrayBuffer();
    await writeFile(filePath, Buffer.from(fileContentBuffer));

    this.log(`Successfully saved file to: ${filePath}`);

    return {
      fileName,
      filePath,
    };
  }

  async deleteFile(filePath: string): Promise<void> {
    this.log(`Attempting to delete file at path: ${filePath}`);
    try {
      await unlink(filePath);
      this.log(`Successfully deleted file at path: ${filePath}`);
    } catch (error: unknown) {
      // Treat missing files as already deleted so admin actions remain idempotent.
      if (
        !(error instanceof Error) ||
        !("code" in error) ||
        error.code !== "ENOENT"
      ) {
        throw error;
      }
    }
  }
}
