import { Injectable, Logger } from '@nestjs/common';
import * as fs from 'fs';

@Injectable()
export class LoggerService {
    private readonly logger = new Logger('LoggerService');

    logApiCall(apiName: string) {
        // const timestamp = new Date().toISOString();
        const timestamp = this.formatDate(new Date());
        // const message = `Calling ${apiName} at ${timestamp}`;
        // this.log(apiName, message);
        this.log(`${apiName} at ${timestamp}`);

    }

    log(apiName: string) {
        // Log to console
        this.logger.log(apiName);

        const logData = `\n
                        ${apiName}\n \n
                        =================================\n`;

        // Log to file
        // this.appendToFile(message);
        fs.appendFile('./vendor-log.txt', `${logData}\n`, (err) => {
            if (err) {
                console.error('Error writing to log file:', err);
            }
        });
    }

    formatDate(date) {
        const year = date.getFullYear();
        const month = ('0' + (date.getMonth() + 1)).slice(-2); // Months are zero-indexed
        const day = ('0' + date.getDate()).slice(-2);
        const hours = ('0' + date.getHours()).slice(-2);
        const minutes = ('0' + date.getMinutes()).slice(-2);
        const seconds = ('0' + date.getSeconds()).slice(-2);

        return `${month}-${day}-${year} ${hours}:${minutes}:${seconds}`;
    }
}
