import fs from "fs"
import path from "path"
import { connection } from "./db.js"

const normalizeSchema = async () => {
    try {
        const [appointmentColumns] = await connection.query("SHOW COLUMNS FROM appointments LIKE 'appintment_date'");
        if (appointmentColumns.length > 0) {
            await connection.query("ALTER TABLE appointments CHANGE appintment_date appointment_date DATE NOT NULL");
            console.log("Renamed appointments.appintment_date to appointment_date");
        }

        const [reportColumns] = await connection.query("SHOW COLUMNS FROM medical_report LIKE 'perscription'");
        if (reportColumns.length > 0) {
            await connection.query("ALTER TABLE medical_report CHANGE perscription prescription VARCHAR(255) NOT NULL");
            console.log("Renamed medical_report.perscription to prescription");
        }
    } catch (error) {
        console.error("normalizeSchema error:", error);
    }
}

const initializeDb = async() => {
    try {
        const sqlPath = path.resolve(process.cwd(), "sql", "sql.sql");
        const sql = fs.readFileSync(sqlPath, "utf8");
        await connection.query(sql);
        await normalizeSchema();
        console.log("Database initialized");
    } catch (error) {
        console.error("initializeDb error:", error);
    }
}

export default initializeDb;