// pages/api/auth/login-as.js

import { getSession } from "next-auth/react";
import prisma from '../../../lib/prisma'; // Adjust the path as per your setup

export default async function handler(req, res) {
    const session = await getSession({ req });
    if (session && session.user.role === 'admin') {
        const { userId } = req.body;

        const userToImpersonate = await prisma.publisher.findUnique({
            where: { id: userId }
        });

        if (userToImpersonate) {
            // Create a custom session object for the impersonated user
            const impersonatedSession = {
                ...session,
                user: {
                    ...session.user,
                    id: userToImpersonate.id,
                    email: userToImpersonate.email,
                    name: userToImpersonate.name,
                    role: userToImpersonate.role,
                    // add other necessary fields
                },
                impersonating: true, // flag to indicate impersonation
                originalUser: session.user // save the original user for later
            };
            // Log the event (simplified example)
            console.log(`Admin ${session.user} impersonated user ${userToImpersonate.email} on ${new Date().toISOString()}`);

            // Here you would typically use some method to create a session server-side
            // For this example, we'll just send the impersonated session as a response
            res.status(200).json({ session: impersonatedSession });
        } else {
            res.status(404).json({ error: 'User not found' });
        }
    } else {
        res.status(403).json({ error: 'Unauthorized' });
    }
}
