import prisma from "@/lib/prisma";
import { User, AdminSession, AuditLog } from "@prisma/client";
import crypto from "crypto";

export class AdminAuthService {
    /**
     * Logs an action to the AuditLog table
     */
    static async logAction(data: {
        userId?: string;
        action: string;
        resourceType: string;
        resourceId?: string;
        details?: Record<string, unknown>;
        ipAddress?: string;
        userAgent?: string;
    }): Promise<AuditLog> {
        return prisma.auditLog.create({
            data: {
                user_id: data.userId,
                action: data.action,
                resource_type: data.resourceType,
                resource_id: data.resourceId,
                details: (data.details || {}) as any,
                ip_address: data.ipAddress,
                user_agent: data.userAgent,
            },
        });
    }

    /**
     * Creates or updates an AdminSession
     */
    static async createSession(
        userId: string,
        status: "active" | "2fa_required",
        reqData: { ipAddress?: string; userAgent?: string; deviceId?: string }
    ): Promise<AdminSession> {
        // Shorter session expiry (2 hours)
        const expiresAt = new Date();
        expiresAt.setHours(expiresAt.getHours() + 2);

        const JWT_SECRET = process.env.JWT_SECRET;
        if (!JWT_SECRET) throw new Error("JWT_SECRET is not configured");
        const secret = new TextEncoder().encode(JWT_SECRET);

        // Use jose to create a verifiable JWT for Edge middleware
        const { SignJWT } = await import('jose');
        const token = await new SignJWT({ userId, status })
            .setProtectedHeader({ alg: 'HS256' })
            .setIssuedAt()
            .setExpirationTime('2h')
            .sign(secret);

        return prisma.adminSession.create({
            data: {
                user_id: userId,
                token,
                status,
                expires_at: expiresAt,
                ip_address: reqData.ipAddress,
                user_agent: reqData.userAgent,
                device_id: reqData.deviceId,
            },
        });
    }

    /**
     * Validates a session token
     */
    static async validateSession(token: string): Promise<{ session: AdminSession; user: User } | null> {
        const session = await prisma.adminSession.findUnique({
            where: { token },
            include: { user: true },
        });

        if (!session) return null;

        // Check expiry
        if (session.expires_at < new Date() || session.status === "expired" || session.status === "revoked") {
            await prisma.adminSession.update({
                where: { id: session.id },
                data: { status: "expired" },
            });
            return null;
        }

        // Refresh last activity
        await prisma.adminSession.update({
            where: { id: session.id },
            data: { last_activity: new Date() },
        });

        return { session, user: session.user };
    }

    /**
     * Invalidates a session
     */
    static async revokeSession(token: string): Promise<void> {
        await prisma.adminSession.updateMany({
            where: { token },
            data: { status: "revoked" },
        });
    }
}
