import db from './lib/db.js';
import { AuditRecord,AuditEngine,FS_ERROR } from './interfaces/index.js';
import { FileEngine } from './engines/index.js';

/**
 * @description Use this on your app to generate and log the audit record
 * @coment This is the main function of the application
 * @comment The audit record is stored in the database,
 * @comment you can provide a custom audit record, or use the generated one
 * @param auditInit - The audit record to be stored, if is empty a new one will be generated
 * @param storagePath - The path where the audit record will be stored, default is the tmp directory SOULD change this for production
 * @env env.HOSTIP - useful to pass the IP address of the end user automatically on docker enviroments
 * @returns AuditRecord | null - The audit record generated or the one provided
 */
export const generateAuditRecord = async (auditInit?: AuditRecord | undefined, dbEngine?:AuditEngine) => {
    try {
    const dbe:AuditEngine = dbEngine || new FileEngine("/tmp");
    const _db = new db(dbe);
    const auditUnit = auditInit?.auditUnit || "gov.gr";
    const auditTransactionId = auditInit?.auditTransactionId || "" + await _db.seq();
    const auditProtocol = auditInit?.auditProtocol || await _db.pn();
    const auditTransactionDate = auditInit?.auditTransactionDate || new Date().toISOString().split('.')[0] + "Z"
    const auditUserIp = auditInit?.auditUserIp || process.env.HOSTIP || "127.0.0.1";
    const auditUserId = auditInit?.auditUserId || "system";
    const auditRecord = {
        auditUnit,
        auditTransactionId,
        auditProtocol,
        auditTransactionDate,
        auditUserIp,
        auditUserId
    }
        return await _db.put(auditRecord);
    } catch (error) {
        const err = error as FS_ERROR;
        console.log(err.code,err.message);
        return null;
    }
}

export default generateAuditRecord;
export { FileEngine } from './engines/index.js';
export { AuditRecord, AuditEngine, DatabaseSettings, FS_ERROR, PNRESETTYPES } from './interfaces/index.js';
