import * as fs from 'fs';
import * as path from 'path';
import { Injectable } from '@nestjs/common';
import type { StorageSettingsVo } from './storage-settings.dto';

const SETTINGS_DIR = path.resolve(process.cwd(), 'config', 'runtime');
const SETTINGS_FILE = path.resolve(SETTINGS_DIR, 'storage.settings.json');

const DEFAULT_SETTINGS: StorageSettingsVo = {
  enabled: false,
  provider: 'local',
  accessKeyId: '',
  accessKeySecret: '',
  bucket: '',
  region: '',
  endpoint: '',
  domain: '',
  folder: '',
  isPrivate: false,
};

@Injectable()
export class StorageSettingsService {
  async getSettings(): Promise<StorageSettingsVo> {
    try {
      const buf = await fs.promises.readFile(SETTINGS_FILE, 'utf8');
      const json = JSON.parse(buf);
      return { ...DEFAULT_SETTINGS, ...json };
    } catch {
      return { ...DEFAULT_SETTINGS };
    }
  }

  async updateSettings(
    patch: Partial<StorageSettingsVo>,
  ): Promise<StorageSettingsVo> {
    const current = await this.getSettings();
    const next: StorageSettingsVo = { ...current, ...patch };
    await fs.promises.mkdir(SETTINGS_DIR, { recursive: true });
    await fs.promises.writeFile(
      SETTINGS_FILE,
      JSON.stringify(next, null, 2),
      'utf8',
    );
    return next;
  }

  static getSettingsPath() {
    return SETTINGS_FILE;
  }
}