import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { AuditLog } from '../audit/entities/audit-log.entity';
import { User } from '../users/entities/user.entity';
import { assertAdmin } from './admin-access';

@Injectable()
export class AdminLogsService {
  constructor(
    @InjectRepository(AuditLog)
    private readonly auditLogsRepository: Repository<AuditLog>,
  ) {}

  async listAuditLogs(actor: User, query: Record<string, unknown>) {
    assertAdmin(actor);
    const page = Math.max(Number(query.page || 1), 1);
    const pageSize = Math.min(Math.max(Number(query.pageSize || 10), 1), 100);
    const actorUsername = String(query.actorUsername || '').trim();
    const action = String(query.action || '').trim();
    const loginResult = String(query.loginResult || '').trim();

    const builder = this.auditLogsRepository
      .createQueryBuilder('log')
      .orderBy('log.createdAt', 'DESC')
      .skip((page - 1) * pageSize)
      .take(pageSize);

    if (actorUsername) {
      builder.andWhere('log.actorUsername LIKE :actorUsername', {
        actorUsername: `%${actorUsername}%`,
      });
    }

    if (action) {
      builder.andWhere('log.action LIKE :action', { action: `%${action}%` });
    }

    if (loginResult) {
      builder.andWhere(
        'log.action = :loginAction AND JSON_UNQUOTE(JSON_EXTRACT(log.metadata, "$.loginResult")) = :loginResult',
        { loginAction: 'auth.login', loginResult },
      );
    }

    const [list, total] = await builder.getManyAndCount();
    return { list, total, page, pageSize };
  }
}
