import { Injectable } from '@nestjs/common';
import { mkdir, access } from 'node:fs/promises';
import { constants } from 'node:fs';
import { join } from 'node:path';
import { AppConfigService } from '../config/config.service';

export interface StorageStatus {
  root: string;
  writable: boolean;
}

@Injectable()
export class LocalFilesystemStorageService {
  constructor(private readonly configService: AppConfigService) {}

  get root(): string {
    return this.configService.storageRoot;
  }

  async checkReadiness(): Promise<StorageStatus> {
    const paths = [
      this.root,
      join(this.root, 'incoming'),
      join(this.root, 'quarantine'),
      join(this.root, 'library', 'audio'),
      join(this.root, 'library', 'artwork'),
      join(this.root, 'temp'),
    ];

    for (const path of paths) {
      await mkdir(path, { recursive: true });
      await access(path, constants.R_OK | constants.W_OK);
    }

    return {
      root: this.root,
      writable: true,
    };
  }
}
