import { Injectable } from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import type { LoginHistory } from 'generated/prisma/client';
import { LoginStatus } from '../types/auth.types';

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

    /**
     * Create login history record
     */
    async createLoginHistory(data: {
        userId: string;
        username: string;
        loginStatus: LoginStatus;
        failedReason?: string;
    }): Promise<LoginHistory> {
        return this.prismaService.loginHistory.create({
            data: {
                userId: data.userId,
                username: data.username,
                loginStatus: data.loginStatus,
                failedReason: data.failedReason,
            },
        });
    }

    /**
     * Get login history for user
     */
    async getUserLoginHistory(
        userId: string,
        limit: number = 10,
        offset: number = 0,
    ) {
        return this.prismaService.loginHistory.findMany({
            where: { userId },
            orderBy: { loginAt: 'desc' },
            take: limit,
            skip: offset,
        });
    }

    /**
     * Get login history count
     */
    async getLoginHistoryCount(userId: string): Promise<number> {
        return this.prismaService.loginHistory.count({
            where: { userId },
        });
    }

    /**
     * Get failed login attempts
     */
    async getFailedLoginAttempts(
        userId: string,
        minutes: number = 15,
    ): Promise<number> {
        const timeAgo = new Date();
        timeAgo.setMinutes(timeAgo.getMinutes() - minutes);

        return this.prismaService.loginHistory.count({
            where: {
                userId,
                loginStatus: 'FAILED',
                loginAt: {
                    gte: timeAgo,
                },
            },
        });
    }

    /**
     * Get successful login count for user
     */
    async getSuccessfulLoginCount(userId: string): Promise<number> {
        return this.prismaService.loginHistory.count({
            where: {
                userId,
                loginStatus: 'SUCCESS',
            },
        });
    }

    /**
     * Get recent successful login
     */
    async getRecentSuccessfulLogin(userId: string) {
        return this.prismaService.loginHistory.findFirst({
            where: {
                userId,
                loginStatus: 'SUCCESS',
            },
            orderBy: { loginAt: 'desc' },
        });
    }
}
