const jwt = require('jsonwebtoken');
const prisma = require('../prisma/PrismaClient.js');
const timeLocal = require('../utils/TimeLocal.js')

const baseLog = async ({ req, action, data }) => {
    // try {
    //     const authHeader = req.headers.authorization;
    //     if (!authHeader || !authHeader.startsWith('Bearer ')) return;

    //     const token = authHeader.split(' ')[1];
    //     const decoded = jwt.decode(token);
    //     if (!decoded?.id || !decoded?.username) return;

    //     await prisma.activityLog.create({
    //         data: {
    //             user_id: decoded.id,
    //             username: decoded.username,
    //             action: JSON.stringify({ [action]: data }),
    //             createdAt: timeLocal.now().toDate(),
    //             updatedAt: timeLocal.now().toDate(),
    //             deletedAt: null,
    //         }
    //     });
    // } catch (err) {
    //     console.error('Failed to log activity:', err.message);
    // }

    try {
        let userId, username;

        // Coba ambil dari Bearer token jika ada
        const authHeader = req?.headers?.authorization;
        if (authHeader?.startsWith('Bearer ')) {
            const token = authHeader.split(' ')[1];
            const decoded = jwt.decode(token);
            userId = decoded?.id;
            username = decoded?.username;
        }

        // Fallback ke data langsung jika belum dapat dari token
        if (!userId || !username) {
            userId = data?.id;
            username = data?.username;
        }

        if (!userId || !username) return;

        await prisma.activityLog.create({
            data: {
                user_id: userId,
                username,
                action: JSON.stringify({ [action]: data }),
                createdAt: timeLocal.now().toDate(),
                updatedAt: timeLocal.now().toDate(),
                deletedAt: null,
            }
        });
    } catch (err) {
        console.error('Failed to log activity:', err.message);
    }
};

const createLog = (req, data) => baseLog({ req, action: 'create', data });
const updateLog = (req, data) => baseLog({ req, action: 'update', data });
const deleteLog = (req, data) => baseLog({ req, action: 'delete', data });
const loginLog = (req, data) => baseLog({ req, action: 'login', data });
const logoutLog = (req, data) => baseLog({ req, action: 'logout', data });

module.exports = { createLog, updateLog, deleteLog, loginLog, logoutLog };