/**
 * ==================================================
 * Smart Attendance System
 * Profile File Service
 * ==================================================
 * Handles Student Profile Storage
 * ==================================================
 */

const fs = require("fs");
const path = require("path");

class ProfileFileService {

    constructor() {

        this.storageRoot = path.join(

            process.cwd(),

            "storage",

            "profiles"

        );

        this.ensureRoot();

    }

    /**
     * ===========================================
     * Create Root Folder
     * ===========================================
     */

    ensureRoot() {

        if (!fs.existsSync(this.storageRoot)) {

            fs.mkdirSync(this.storageRoot, {

                recursive: true

            });

        }

    }

    /**
     * ===========================================
     * Student Folder
     * ===========================================
     */

    ensureStudentFolder(studentId) {

        const directory = path.join(

            this.storageRoot,

            `student_${studentId}`

        );

        if (!fs.existsSync(directory)) {

            fs.mkdirSync(directory, {

                recursive: true

            });

        }

        return directory;

    }

    /**
     * ===========================================
     * Absolute Path
     * ===========================================
     */

    getProfileAbsolutePath(

        studentId,

        extension = ".jpg"

    ) {

        const directory =

            this.ensureStudentFolder(studentId);

        return path.join(

            directory,

            `profile${extension}`

        );

    }

    /**
     * ===========================================
     * Relative Path (Database)
     * ===========================================
     */

    getProfileRelativePath(

        studentId,

        extension = ".jpg"

    ) {

        return `student_${studentId}/profile${extension}`;

    }

    /**
     * ===========================================
     * Public URL
     * ===========================================
     */

    getProfileURL(

        req,

        relativePath

    ) {

        if (!relativePath) {

            return null;

        }

        return `${req.protocol}://${req.get("host")}/profiles/${relativePath}`;

    }

}

module.exports = new ProfileFileService();