import { Injectable } from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import type { UserSession } from 'generated/prisma/client';
import { TokenUtils } from 'src/common/utils/utils.token';

@Injectable()
export class SessionService {
    constructor(private readonly prismaService: PrismaService) { }

    async createSession(data: {
        userId: string;
        token: string;
        createdBy?: string;
    }): Promise<UserSession> {
        const expiredAt = TokenUtils.generateJwtExpiration(24);
        return this.prismaService.userSession.create({
            data: {
                userId: data.userId,
                token: data.token,
                expiredAt,
                createdBy: data.createdBy,
            },
        });
    }

    async findSessionByToken(token: string): Promise<UserSession | null> {
        return this.prismaService.userSession.findFirst({
            where: {
                token,
                expiredAt: {
                    gt: new Date(),
                },
            },
        });
    }

    async findSessionByUserId(userId: string) {
        return this.prismaService.userSession.findMany({
            where: {
                userId,
                expiredAt: {
                    gt: new Date(),
                },
            },
        });
    }

    async invalidateSession(token: string): Promise<void> {
        await this.prismaService.userSession.deleteMany({
            where: { token },
        });
    }

    async invalidateAllUserSessions(userId: string): Promise<void> {
        await this.prismaService.userSession.deleteMany({
            where: { userId },
        });
    }

    async cleanupExpiredSessions(): Promise<void> {
        await this.prismaService.userSession.deleteMany({
            where: {
                expiredAt: {
                    lt: new Date(),
                },
            },
        });
    }

    async getActiveSessionsCount(userId: string): Promise<number> {
        return this.prismaService.userSession.count({
            where: {
                userId,
                expiredAt: {
                    gt: new Date(),
                },
            },
        });
    }
}
