import type { Request } from "express";
import jwt from "jsonwebtoken";
import { prisma } from "../config/db.ts";
import path from "path";
import os from "os";

export function signToken(user: any, sessionToken: string) {
    const JWT_SECRET = process.env.JWT_SECRET as string;

    return jwt.sign(
        {
            id: user.id,
            email: user.email,
            role: user.role,
            sessionToken,
            institutionId: user.institutionId,
        },
        JWT_SECRET,
        { expiresIn: "1d" }
    );
}

export const getHost = (): string => {
    const ip = Object.values(os.networkInterfaces())
        .flat()
        .find(i => i.family === 'IPv4' && !i.internal)?.address || 'localhost';
    const port = process.env.PORT || 5173;
    return `http://${ip}:${port}`;
};

export const generateReferralCode = async (length = 8): Promise<string> => {
    const chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
    // removed O, 0, I, 1 to avoid confusion

    while (true) {
        let code = "";
        for (let i = 0; i < length; i++) {
            code += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        const existingStaff = await prisma.staff.findFirst({
            where: { referralCode: code },
            select: { id: true }
        });
        if (!existingStaff) {
            return code;
        }
    }
};

// File Custom Path Fetch
// export const toPublicPath = (filePath: string | undefined) => {
//     if (!filePath) return null;

//     const normalized = path.normalize(filePath);
//     const parts = normalized.split(path.sep);
//     const uploadsIndex = parts.lastIndexOf("uploads");

//     if (uploadsIndex === -1) return null;

//     return "/" + parts.slice(uploadsIndex).join("/").replace(/\\/g, "/");
// };

export const toPublicPath = (filePath?: string) => {
    if (!filePath) return null;

    // Convert Windows slashes to URL slashes
    const normalized = filePath.replace(/\\/g, "/");

    // Find uploads folder
    const uploadsIndex = normalized.lastIndexOf("/uploads/");

    // Handle path starting directly with uploads/
    if (uploadsIndex !== -1) {
        return normalized.substring(uploadsIndex);
    }

    // Handle paths like uploads/file.png
    if (normalized.startsWith("uploads/")) {
        return "/" + normalized;
    }

    return null;
};