"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const sdk_1 = require("@prisma/sdk");
const fs = tslib_1.__importStar(require("fs"));
// import chalk from 'chalk';
const chalk_1 = tslib_1.__importDefault(require("chalk"));
const path = tslib_1.__importStar(require("path"));
const fastify_1 = tslib_1.__importDefault(require("fastify"));
const open_1 = tslib_1.__importDefault(require("open"));
const server = fastify_1.default({});
function getSchemaPath(schemaPath) {
    if (schemaPath && fs.existsSync(schemaPath)) {
        return schemaPath;
    }
    const paths = ["./schema.prisma", "./prisma/schema.prisma"];
    for (const path of paths) {
        if (fs.existsSync(path)) {
            return path;
        }
    }
    throw Error(chalk_1.default.red("✗ Schema could not be found!"));
}
class Run {
    static new() {
        return new Run();
    }
    constructor() { }
    async parse(args) {
        let datamodelPath = getSchemaPath(args && args[0]);
        const dmmf = await sdk_1.getDMMF({ datamodelPath });
        fs.writeFileSync(path.join(__dirname, '../../public/datamodel.json'), JSON.stringify(dmmf.datamodel), { encoding: 'utf8', flag: 'w' });
        console.log(chalk_1.default.green('✔ Data Model Generated'));
        // Require the framework and instantiate it
        server.register(require('fastify-static'), {
            root: path.join(__dirname, '../../public'),
            prefix: '/public/',
        });
        // Declare a route
        server.get('/', async (request, reply) => {
            reply.sendFile('index.html'); // serving path.join(__dirname, 'public', 'myHtml.html') directly
        });
        server.post('/generate', async (request, reply) => {
            const schema = request.body;
            try {
                const dmmf = await sdk_1.getDMMF({ datamodel: schema });
                reply
                    .code(200)
                    .header('Content-Type', 'application/json; charset=utf-8')
                    .send(dmmf.datamodel);
            }
            catch (err) {
                reply
                    .code(500)
                    .send(err);
            }
        });
        // Run the server!
        const start = async () => {
            var _a, _b;
            try {
                await server.listen(3000);
                let address = server.server.address();
                address = typeof address === 'string' ? address : `${(_a = address) === null || _a === void 0 ? void 0 : _a.address}:${(_b = address) === null || _b === void 0 ? void 0 : _b.port}`;
                const url = `http://${address}`;
                return url;
            }
            catch (err) {
                process.exit(1);
            }
        };
        const url = await start();
        console.log(chalk_1.default.green(`✔ Opening Browser to ${url}`));
        await open_1.default(url);
        return '';
    }
}
exports.Run = Run;
