"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var DatabaseBootstrapService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.DatabaseBootstrapService = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("typeorm");
const promises_1 = require("fs/promises");
const path = __importStar(require("path"));
const typeorm_2 = require("@nestjs/typeorm");
let DatabaseBootstrapService = DatabaseBootstrapService_1 = class DatabaseBootstrapService {
    constructor(dataSource) {
        this.dataSource = dataSource;
        this.logger = new common_1.Logger(DatabaseBootstrapService_1.name);
    }
    async onModuleInit() {
        if (!this.dataSource.isInitialized) {
            this.logger.warn(`[${this.dataSource.name}] DataSource not initialized. Skipping SQL bootstrap.`);
            return;
        }
        this.logger.debug(`[${this.dataSource.name}] Bootstrapping stored procedures...`);
        await this.applyAllSqlFiles();
        this.logger.debug(`[${this.dataSource.name}] SQL bootstrap completed`);
    }
    resolveSqlDirectory() {
        const datasourceName = this.dataSource.name || 'default';
        const dbType = this.dataSource.options.type;
        const sqlFilePath = path.resolve(__dirname, `../../../sql/${datasourceName}/${dbType}`);
        return sqlFilePath;
    }
    async applyAllSqlFiles() {
        const sqlDir = this.resolveSqlDirectory();
        this.logger.debug(`[${this.dataSource.name}] SQL directory: ${sqlDir}`);
        let files;
        try {
            files = await (0, promises_1.readdir)(sqlDir);
        }
        catch {
            this.logger.warn(`[${this.dataSource.name}] No SQL directory found. Skipping.`);
            return;
        }
        const sqlFiles = files
            .filter(file => file.endsWith('.sql'))
            .sort();
        if (!sqlFiles.length) {
            this.logger.warn(`[${this.dataSource.name}] No SQL files found`);
            return;
        }
        for (const file of sqlFiles) {
            await this.applySqlFileSafely(path.join(sqlDir, file), file);
        }
    }
    async applySqlFileSafely(filePath, fileName) {
        this.logger.debug(`[${this.dataSource.name}] Applying ${fileName}`);
        try {
            const sql = await (0, promises_1.readFile)(filePath, 'utf8');
            await this.dataSource.query(sql);
            this.logger.debug(`[${this.dataSource.name}] Applied ${fileName}`);
        }
        catch (error) {
            this.logger.error(`[${this.dataSource.name}] Failed ${fileName}`, error instanceof Error ? error.stack : String(error));
        }
    }
};
exports.DatabaseBootstrapService = DatabaseBootstrapService;
exports.DatabaseBootstrapService = DatabaseBootstrapService = DatabaseBootstrapService_1 = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_2.InjectDataSource)()),
    __metadata("design:paramtypes", [typeorm_1.DataSource])
], DatabaseBootstrapService);
//# sourceMappingURL=database-bootstrap.service.js.map