import { Injectable } from "@nestjs/common";
import { Prisma, AuditAction } from "@prisma/client";
import { PrismaService } from "../database/prisma.service.js";

/**
 * Service for reading and querying audit log entries.
 *
 * Handles all audit read operations: paginated log retrieval
 * and security analytics/statistics.
 */
@Injectable()
export class AuditQueryService {
  constructor(private readonly prisma: PrismaService) {}

  async getAuditLogs({
    page,
    limit,
    action,
    userId,
  }: {
    page: number;
    limit: number;
    action?: AuditAction;
    userId?: string;
  }) {
    const skip = (page - 1) * limit;
    const where: Prisma.AuditLogWhereInput = {};
    if (action) where.action = action;
    if (userId) where.userId = userId;

    const [logs, total] = await Promise.all([
      this.prisma.auditLog.findMany({
        where,
        include: {
          user: {
            select: {
              id: true,
              email: true,
            },
          },
        },
        orderBy: { createdAt: "desc" },
        skip,
        take: limit,
      }),
      this.prisma.auditLog.count({ where }),
    ]);

    return { logs, total };
  }

  async getSecurityStats() {
    const today = new Date(new Date().setHours(0, 0, 0, 0));

    const [totalUsers, lockedAccounts, failedLoginsToday, successfulLoginsToday] =
      await Promise.all([
        this.prisma.user.count(),
        this.prisma.user.count({
          where: {
            lockedUntil: {
              gt: new Date(),
            },
          },
        }),
        this.prisma.auditLog.count({
          where: {
            action: AuditAction.LOGIN_FAILED,
            createdAt: {
              gte: today,
            },
          },
        }),
        this.prisma.auditLog.count({
          where: {
            action: AuditAction.LOGIN_SUCCESS,
            createdAt: {
              gte: today,
            },
          },
        }),
      ]);

    return {
      totalUsers,
      lockedAccounts,
      failedLoginsToday,
      successfulLoginsToday,
      securityEventsToday: failedLoginsToday + successfulLoginsToday,
    };
  }
}
