import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { S3Client, PutObjectCommand, DeleteObjectCommand } from '@aws-sdk/client-s3';

@Injectable()
export class NcpStorageService {
  private readonly logger = new Logger(NcpStorageService.name);
  private readonly s3: S3Client;
  private readonly bucket: string;
  private readonly cdnDomain: string;

  constructor(private configService: ConfigService) {
    const endpoint = this.configService.get('NCP_ENDPOINT') || 'https://kr.object.ncloudstorage.com';
    const accessKey = this.configService.get('NCP_ACCESS_KEY') || '';
    const secretKey = this.configService.get('NCP_SECRET_KEY') || '';

    this.bucket = this.configService.get('NCP_BUCKET_NAME') || 'freeflow';
    this.cdnDomain = this.configService.get('NCP_CDN_DOMAIN') || `${endpoint}/${this.bucket}`;

    this.s3 = new S3Client({
      endpoint,
      region: 'kr-standard',
      credentials: {
        accessKeyId: accessKey,
        secretAccessKey: secretKey,
      },
      forcePathStyle: true,
    });
  }

  async upload(buffer: Buffer, key: string, contentType: string): Promise<string> {
    await this.s3.send(new PutObjectCommand({
      Bucket: this.bucket,
      Key: key,
      Body: buffer,
      ContentType: contentType,
      ACL: 'public-read',
    }));

    const url = `${this.cdnDomain}/${key}`;
    this.logger.log(`Uploaded: ${key} → ${url}`);
    return url;
  }

  async delete(key: string): Promise<void> {
    try {
      await this.s3.send(new DeleteObjectCommand({
        Bucket: this.bucket,
        Key: key,
      }));
      this.logger.log(`Deleted: ${key}`);
    } catch (err) {
      this.logger.error(`Delete failed: ${key}`, err);
    }
  }
}
