"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.deleteSchool = exports.updateSchool = exports.getAllSchools = exports.createSchool = void 0;
const school_1 = require("../models/school");
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
/// Create new school
const createSchool = async (req, res) => {
    // Handle file upload
    if (!req.file) {
        return res.status(400).json({ error: "Logo file is required." });
    }
    const fileUrl = `${req.protocol}://${req.get("host")}/uploads/${req.file.filename}`;
    req.body.logo = fileUrl;
    // Validate the request body (without logo for now)
    const { error } = school_1.schoolValidationSchema.validate(req.body);
    if (error) {
        const filePath = path_1.default.join("uploads", req.file.filename);
        fs_1.default.unlinkSync(filePath);
        return res.status(400).json({ error: error.details[0].message });
    }
    // Create and save the new school
    try {
        const newSchool = await school_1.SchoolModel.create(req.body);
        return res
            .status(200)
            .json({ message: "School created successfully.", id: newSchool.id });
    }
    catch (ex) {
        return res.status(500).json({ error: "An unexpected error occurred." });
    }
};
exports.createSchool = createSchool;
/// Get all schools
const getAllSchools = async (req, res) => {
    console.log(`We reached here to get data`);
    try {
        const schools = await school_1.SchoolModel.findAll({ where: { isDeleted: 0 } });
        return res.status(200).json(schools);
    }
    catch (ex) {
        return res.status(500).json({ error: "An unexpected error occurred." });
    }
};
exports.getAllSchools = getAllSchools;
/// Update existing school
const updateSchool = async (req, res) => {
    try {
        // Find the school by ID
        const school = await school_1.SchoolModel.findByPk(req.params.id);
        if (!school)
            return res.status(404).json({ error: "School not found." });
        // Handle file upload if provided
        if (req.file) {
            // Sirf tab purana file delete karo agar local file hai, http URL nahi
            if (!req.file.fieldname.startsWith("http")) {
                const oldFilename = path_1.default.basename(school.logo);
                const oldPath = path_1.default.join("uploads", oldFilename);
                fs_1.default.unlinkSync(oldPath);
            }
            // Update logo URL
            const fileUrl = `${req.protocol}://${req.get("host")}/uploads/${req.file.filename}`;
            req.body.logo = fileUrl;
        }
        // Validate the request body
        const { error } = school_1.schoolValidationSchema.validate(req.body);
        if (error) {
            // Agar file upload hui thi, delete newly uploaded file
            if (req.file) {
                const filePath = path_1.default.join("uploads", req.file.filename);
                if (fs_1.default.existsSync(filePath))
                    fs_1.default.unlinkSync(filePath);
            }
            return res.status(400).json({ error: error.details[0].message });
        }
        // Update the school details
        await school.update(req.body);
        // Send success response
        return res
            .status(200)
            .json({ message: "School updated successfully.", id: school.id });
    }
    catch (ex) {
        console.error(`Here is error: ${ex}`);
        return res.status(500).json({ error: "An unexpected error occurred." });
    }
};
exports.updateSchool = updateSchool;
/// Delete a school
const deleteSchool = async (req, res) => {
    try {
        // Find the school by ID
        const school = await school_1.SchoolModel.findByPk(req.params.id);
        if (!school)
            return res.status(404).json({ error: "School not found." });
        // Soft delete the school
        await school.update({ isDeleted: true });
        // Send success response
        return res.status(200).json({ message: "School deleted successfully." });
    }
    catch (ex) {
        return res.status(500).json({ error: "An unexpected error occurred." });
    }
};
exports.deleteSchool = deleteSchool;
