import { Injectable, Logger } from '@nestjs/common';
import { stringify } from 'csv-stringify/sync';
import * as path from 'path';
import * as fs from 'fs';
import { ConfigService } from '@nestjs/config';

export interface CsvColumn {
  header: string;
  key: string;
}

export interface CsvExportOptions {
  columns: CsvColumn[];
  data: any[];
}

@Injectable()
export class CsvExportService {
  private readonly logger = new Logger(CsvExportService.name);
  private readonly storagePath: string;

  constructor(private readonly configService: ConfigService) {
    this.storagePath = this.configService.get<string>(
      'FILE_STORAGE_PATH',
      './storage/reports',
    );
  }

  async export(
    fileName: string,
    options: CsvExportOptions,
  ): Promise<{ filePath: string; fileSize: number }> {
    const headers = options.columns.map((col) => col.header);
    const keys = options.columns.map((col) => col.key);

    const rows = options.data.map((item) =>
      keys.map((key) => {
        const value = item[key];
        if (value === null || value === undefined) {
          return '';
        }
        if (typeof value === 'object') {
          return JSON.stringify(value);
        }
        return String(value);
      }),
    );

    const csvContent = stringify([headers, ...rows]);

    // Add BOM for Excel compatibility with Chinese characters
    const bom = '\uFEFF';
    const contentWithBom = bom + csvContent;

    // Ensure storage directory exists
    const fullPath = path.join(this.storagePath, fileName);
    const dir = path.dirname(fullPath);
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
    }

    // Write file
    fs.writeFileSync(fullPath, contentWithBom, 'utf8');

    const stats = fs.statSync(fullPath);

    this.logger.log(`CSV file exported: ${fullPath} (${stats.size} bytes)`);

    return {
      filePath: fullPath,
      fileSize: stats.size,
    };
  }
}
