"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var AccessLogService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.AccessLogService = void 0;
const api_pagination_1 = require("@hed-hog/api-pagination");
const api_prisma_1 = require("@hed-hog/api-prisma");
const common_1 = require("@nestjs/common");
let AccessLogService = AccessLogService_1 = class AccessLogService {
    constructor(prisma, pagination) {
        this.prisma = prisma;
        this.pagination = pagination;
        this.logger = new common_1.Logger(AccessLogService_1.name);
    }
    recordHttp(data) {
        var _a, _b, _c;
        this.prisma.access_log
            .create({
            data: {
                user_id: (_a = data.userId) !== null && _a !== void 0 ? _a : null,
                ip: (_b = data.ip) !== null && _b !== void 0 ? _b : null,
                user_agent: (_c = data.userAgent) !== null && _c !== void 0 ? _c : null,
                method: data.method,
                path: data.path,
            },
        })
            .catch((e) => this.logger.warn(`Failed to persist HTTP access log: ${e.message}`));
    }
    recordMcp(data) {
        var _a, _b;
        this.prisma.access_log
            .create({
            data: {
                user_id: (_a = data.userId) !== null && _a !== void 0 ? _a : null,
                mcp_tool: data.mcpTool,
                mcp_prompt: (_b = data.mcpPrompt) !== null && _b !== void 0 ? _b : null,
            },
        })
            .catch((e) => this.logger.warn(`Failed to persist MCP access log: ${e.message}`));
    }
    async list(params) {
        var _a;
        const where = {};
        if (params.userId) {
            where.user_id = params.userId;
        }
        if (params.userSearch) {
            where.user = {
                OR: [
                    { name: { contains: params.userSearch, mode: 'insensitive' } },
                ],
            };
        }
        if (params.createdAtFrom || params.createdAtTo) {
            where.created_at = {};
            if (params.createdAtFrom) {
                where.created_at.gte = new Date(params.createdAtFrom);
            }
            if (params.createdAtTo) {
                const to = new Date(params.createdAtTo);
                to.setHours(23, 59, 59, 999);
                where.created_at.lte = to;
            }
        }
        if (params.type === 'http') {
            where.method = { not: null };
        }
        else if (params.type === 'mcp') {
            where.mcp_tool = { not: null };
        }
        return this.pagination.paginate(this.prisma.access_log, Object.assign(Object.assign({}, params), { fields: (_a = params.fields) !== null && _a !== void 0 ? _a : '' }), {
            where,
            orderBy: { created_at: 'desc' },
            include: {
                user: { select: { id: true, name: true, photo_id: true } },
            },
        });
    }
    async clearOld(retentionDays, batchLimit) {
        await this.prisma.$executeRaw `
      WITH del AS (
        SELECT id
        FROM access_log
        WHERE created_at < (now() - ${api_prisma_1.Prisma.sql `INTERVAL '${api_prisma_1.Prisma.raw(String(retentionDays))} days'`})
        ORDER BY id
        LIMIT ${batchLimit}
      )
      DELETE FROM access_log al
      USING del
      WHERE al.id = del.id
    `;
    }
};
exports.AccessLogService = AccessLogService;
exports.AccessLogService = AccessLogService = AccessLogService_1 = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, common_1.Inject)((0, common_1.forwardRef)(() => api_prisma_1.PrismaService))),
    __param(1, (0, common_1.Inject)((0, common_1.forwardRef)(() => api_pagination_1.PaginationService))),
    __metadata("design:paramtypes", [api_prisma_1.PrismaService,
        api_pagination_1.PaginationService])
], AccessLogService);
//# sourceMappingURL=access-log.service.js.map