"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); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SessionsController = void 0;
const common_1 = require("@nestjs/common");
const platform_express_1 = require("@nestjs/platform-express");
require("multer");
const swagger_1 = require("@nestjs/swagger");
const sessions_service_1 = require("./sessions.service");
const session_dto_1 = require("./dto/session.dto");
const core_entities_1 = require("../core-entities");
const session_transfer_service_1 = require("../session-transfer/session-transfer.service");
const session_followup_service_1 = require("../session-followup/session-followup.service");
let SessionsController = class SessionsController {
    constructor(sessionsService, sessionTransferService, sessionFollowupService) {
        this.sessionsService = sessionsService;
        this.sessionTransferService = sessionTransferService;
        this.sessionFollowupService = sessionFollowupService;
    }
    async create(createSessionDto) {
        return this.sessionsService.create(createSessionDto);
    }
    async setActive(id) {
        await this.sessionsService.setActive(id);
        return { success: true };
    }
    async importSession(file) {
        if (!file) {
            throw new common_1.BadRequestException('No file uploaded.');
        }
        try {
            const fileContent = JSON.parse(file.buffer.toString('utf-8'));
            return this.sessionTransferService.importSession(fileContent);
        }
        catch (e) {
            throw new common_1.BadRequestException(`Invalid JSON file: ${e.message}`);
        }
    }
    async createFromContext(id, createDto) {
        return this.sessionFollowupService.createFromContext(id, createDto);
    }
    async findActive(res) {
        const session = await this.sessionsService.findActive();
        if (session) {
            return res.status(common_1.HttpStatus.OK).json(session);
        }
        else {
            return res.status(common_1.HttpStatus.NO_CONTENT).send();
        }
    }
    async findAll(filter, limit) {
        const parsedLimit = limit ? parseInt(limit, 10) : undefined;
        return this.sessionsService.findAll(filter, parsedLimit);
    }
    async findOne(id, includeLogs) {
        const includeExecutionLogs = includeLogs === 'true';
        return this.sessionsService.findOne(id, includeExecutionLogs);
    }
    async findChildSessions(id) {
        return this.sessionsService.findChildSessions(id);
    }
    async getFileChanges(id) {
        return this.sessionsService.getFileChanges(id);
    }
    async exportSession(id, res) {
        const data = await this.sessionTransferService.exportSession(id);
        const fileName = `session-export-${id}.json`;
        res.setHeader('Content-Disposition', `attachment; filename=${fileName}`);
        res.setHeader('Content-Type', 'application/json');
        res.send(JSON.stringify(data, null, 2));
    }
    async update(id, updateSessionDto) {
        return this.sessionsService.update(id, updateSessionDto);
    }
    async remove(id) {
        return this.sessionsService.remove(id);
    }
    async clone(id) {
        return this.sessionsService.cloneSession(id);
    }
    async revertFile(id, revertFileDto) {
        await this.sessionsService.revertFile(id, revertFileDto.file_path);
        return { success: true, file_path: revertFileDto.file_path };
    }
    async revertSession(id) {
        return this.sessionsService.revertSession(id);
    }
    async getInputFileChanges(id, inputIds) {
        if (!inputIds) {
            throw new common_1.BadRequestException('No input IDs provided');
        }
        const parsedInputIds = inputIds
            .split(',')
            .map((s) => s.trim())
            .filter((s) => s.length > 0);
        if (parsedInputIds.length === 0) {
            throw new common_1.BadRequestException('No input IDs provided');
        }
        return this.sessionsService.getInputFileChanges(id, parsedInputIds);
    }
    async revertInputFileChanges(id, inputIds) {
        if (!inputIds || inputIds.length === 0) {
            throw new common_1.BadRequestException('No input IDs provided');
        }
        return this.sessionsService.revertInputFileChanges(id, inputIds);
    }
};
exports.SessionsController = SessionsController;
__decorate([
    (0, common_1.Post)(),
    (0, swagger_1.ApiOperation)({ summary: 'Create a new session' }),
    (0, swagger_1.ApiResponse)({
        status: 201,
        description: 'Session created successfully',
        type: core_entities_1.Session,
    }),
    __param(0, (0, common_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [session_dto_1.CreateSessionDto]),
    __metadata("design:returntype", Promise)
], SessionsController.prototype, "create", null);
__decorate([
    (0, common_1.Post)(':id/set-active'),
    (0, common_1.HttpCode)(common_1.HttpStatus.OK),
    (0, swagger_1.ApiOperation)({ summary: 'Set a session as the active session' }),
    (0, swagger_1.ApiParam)({ name: 'id', description: 'Session UUID', format: 'uuid' }),
    (0, swagger_1.ApiResponse)({
        status: 200,
        description: 'Session set as active',
        schema: { properties: { success: { type: 'boolean' } } },
    }),
    __param(0, (0, common_1.Param)('id', common_1.ParseUUIDPipe)),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], SessionsController.prototype, "setActive", null);
__decorate([
    (0, common_1.Post)('import'),
    (0, swagger_1.ApiOperation)({ summary: 'Import a session from a JSON file' }),
    (0, swagger_1.ApiConsumes)('multipart/form-data'),
    (0, swagger_1.ApiBody)({
        schema: {
            type: 'object',
            properties: { file: { type: 'string', format: 'binary' } },
        },
    }),
    (0, swagger_1.ApiResponse)({
        status: 201,
        description: 'Session imported successfully',
        type: session_dto_1.ImportSessionResponseDto,
    }),
    (0, swagger_1.ApiResponse)({ status: 400, description: 'Invalid file or missing file' }),
    (0, common_1.UseInterceptors)((0, platform_express_1.FileInterceptor)('file')),
    __param(0, (0, common_1.UploadedFile)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], SessionsController.prototype, "importSession", null);
__decorate([
    (0, common_1.Post)(':id/create-from-context'),
    (0, common_1.HttpCode)(common_1.HttpStatus.CREATED),
    (0, swagger_1.ApiOperation)({
        summary: 'Create a follow-up session from an existing session context',
    }),
    (0, swagger_1.ApiParam)({ name: 'id', description: 'Parent session UUID', format: 'uuid' }),
    (0, swagger_1.ApiResponse)({
        status: 201,
        description: 'Follow-up session created',
        type: core_entities_1.Session,
    }),
    __param(0, (0, common_1.Param)('id', common_1.ParseUUIDPipe)),
    __param(1, (0, common_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, session_dto_1.CreateSessionFromContextDto]),
    __metadata("design:returntype", Promise)
], SessionsController.prototype, "createFromContext", null);
__decorate([
    (0, common_1.Get)('active'),
    (0, swagger_1.ApiOperation)({ summary: 'Get the currently active session' }),
    (0, swagger_1.ApiResponse)({
        status: 200,
        description: 'Active session found',
        type: core_entities_1.Session,
    }),
    (0, swagger_1.ApiResponse)({ status: 204, description: 'No active session' }),
    __param(0, (0, common_1.Res)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], SessionsController.prototype, "findActive", null);
__decorate([
    (0, common_1.Get)(),
    (0, swagger_1.ApiOperation)({ summary: 'List all sessions' }),
    (0, swagger_1.ApiQuery)({
        name: 'filter',
        required: false,
        description: 'Filter: "non-empty" = sessions with inputs; "recent" = running + last N non-running',
    }),
    (0, swagger_1.ApiQuery)({
        name: 'limit',
        required: false,
        description: 'Max non-running sessions to return when filter=recent (default: 10, max: 100)',
        type: String,
    }),
    (0, swagger_1.ApiResponse)({
        status: 200,
        description: 'List of sessions',
        type: [core_entities_1.Session],
    }),
    __param(0, (0, common_1.Query)('filter')),
    __param(1, (0, common_1.Query)('limit')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String]),
    __metadata("design:returntype", Promise)
], SessionsController.prototype, "findAll", null);
__decorate([
    (0, common_1.Get)(':id'),
    (0, swagger_1.ApiOperation)({ summary: 'Get a session by ID' }),
    (0, swagger_1.ApiParam)({ name: 'id', description: 'Session UUID', format: 'uuid' }),
    (0, swagger_1.ApiQuery)({
        name: 'includeLogs',
        required: false,
        description: 'Include executionLogs in actions (default: false for performance)',
        type: Boolean,
    }),
    (0, swagger_1.ApiResponse)({ status: 200, description: 'Session found', type: core_entities_1.Session }),
    (0, swagger_1.ApiResponse)({ status: 404, description: 'Session not found' }),
    __param(0, (0, common_1.Param)('id', common_1.ParseUUIDPipe)),
    __param(1, (0, common_1.Query)('includeLogs')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String]),
    __metadata("design:returntype", Promise)
], SessionsController.prototype, "findOne", null);
__decorate([
    (0, common_1.Get)(':id/child-sessions'),
    (0, swagger_1.ApiOperation)({ summary: 'Get all child sessions of a session' }),
    (0, swagger_1.ApiParam)({ name: 'id', description: 'Parent session UUID', format: 'uuid' }),
    (0, swagger_1.ApiResponse)({
        status: 200,
        description: 'List of child sessions',
        type: [core_entities_1.Session],
    }),
    __param(0, (0, common_1.Param)('id', common_1.ParseUUIDPipe)),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], SessionsController.prototype, "findChildSessions", null);
__decorate([
    (0, common_1.Get)(':id/file-changes'),
    (0, swagger_1.ApiOperation)({ summary: 'Get file changes made in a session' }),
    (0, swagger_1.ApiParam)({ name: 'id', description: 'Session UUID', format: 'uuid' }),
    (0, swagger_1.ApiResponse)({
        status: 200,
        description: 'List of file changes',
        schema: {
            type: 'array',
            items: {
                type: 'object',
                properties: {
                    file_path: { type: 'string' },
                    initial_content: { type: 'string', nullable: true },
                    current_content: { type: 'string', nullable: true },
                },
            },
        },
    }),
    __param(0, (0, common_1.Param)('id', common_1.ParseUUIDPipe)),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], SessionsController.prototype, "getFileChanges", null);
__decorate([
    (0, common_1.Get)(':id/export'),
    (0, swagger_1.ApiOperation)({ summary: 'Export a session to JSON' }),
    (0, swagger_1.ApiParam)({ name: 'id', description: 'Session UUID', format: 'uuid' }),
    (0, swagger_1.ApiResponse)({ status: 200, description: 'Session exported as JSON file' }),
    __param(0, (0, common_1.Param)('id', common_1.ParseUUIDPipe)),
    __param(1, (0, common_1.Res)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Object]),
    __metadata("design:returntype", Promise)
], SessionsController.prototype, "exportSession", null);
__decorate([
    (0, common_1.Put)(':id'),
    (0, swagger_1.ApiOperation)({ summary: 'Update a session' }),
    (0, swagger_1.ApiParam)({ name: 'id', description: 'Session UUID', format: 'uuid' }),
    (0, swagger_1.ApiResponse)({
        status: 200,
        description: 'Session updated successfully',
        type: core_entities_1.Session,
    }),
    (0, swagger_1.ApiResponse)({ status: 404, description: 'Session not found' }),
    __param(0, (0, common_1.Param)('id', common_1.ParseUUIDPipe)),
    __param(1, (0, common_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, session_dto_1.UpdateSessionDto]),
    __metadata("design:returntype", Promise)
], SessionsController.prototype, "update", null);
__decorate([
    (0, common_1.Delete)(':id'),
    (0, common_1.HttpCode)(common_1.HttpStatus.NO_CONTENT),
    (0, swagger_1.ApiOperation)({ summary: 'Delete a session' }),
    (0, swagger_1.ApiParam)({ name: 'id', description: 'Session UUID', format: 'uuid' }),
    (0, swagger_1.ApiResponse)({ status: 204, description: 'Session deleted successfully' }),
    (0, swagger_1.ApiResponse)({ status: 404, description: 'Session not found' }),
    __param(0, (0, common_1.Param)('id', common_1.ParseUUIDPipe)),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], SessionsController.prototype, "remove", null);
__decorate([
    (0, common_1.Post)(':id/clone'),
    (0, swagger_1.ApiOperation)({ summary: 'Clone a session' }),
    (0, swagger_1.ApiParam)({
        name: 'id',
        description: 'Session UUID to clone',
        format: 'uuid',
    }),
    (0, swagger_1.ApiResponse)({
        status: 201,
        description: 'Session cloned successfully',
        type: core_entities_1.Session,
    }),
    (0, swagger_1.ApiResponse)({ status: 404, description: 'Session not found' }),
    __param(0, (0, common_1.Param)('id', common_1.ParseUUIDPipe)),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], SessionsController.prototype, "clone", null);
__decorate([
    (0, common_1.Post)(':id/revert-file'),
    (0, common_1.HttpCode)(common_1.HttpStatus.OK),
    (0, swagger_1.ApiOperation)({ summary: 'Revert a specific file changed in the session' }),
    (0, swagger_1.ApiParam)({ name: 'id', description: 'Session UUID', format: 'uuid' }),
    (0, swagger_1.ApiBody)({ type: session_dto_1.RevertFileDto }),
    (0, swagger_1.ApiResponse)({
        status: 200,
        description: 'File reverted successfully',
        schema: {
            properties: {
                success: { type: 'boolean' },
                file_path: { type: 'string' },
            },
        },
    }),
    (0, swagger_1.ApiResponse)({ status: 404, description: 'Session or file not found' }),
    __param(0, (0, common_1.Param)('id', common_1.ParseUUIDPipe)),
    __param(1, (0, common_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, session_dto_1.RevertFileDto]),
    __metadata("design:returntype", Promise)
], SessionsController.prototype, "revertFile", null);
__decorate([
    (0, common_1.Post)(':id/revert-session'),
    (0, common_1.HttpCode)(common_1.HttpStatus.OK),
    (0, swagger_1.ApiOperation)({ summary: 'Revert all file changes made in the session' }),
    (0, swagger_1.ApiParam)({ name: 'id', description: 'Session UUID', format: 'uuid' }),
    (0, swagger_1.ApiResponse)({
        status: 200,
        description: 'Session changes reverted',
        type: session_dto_1.RevertSessionResponseDto,
    }),
    (0, swagger_1.ApiResponse)({ status: 404, description: 'Session not found' }),
    __param(0, (0, common_1.Param)('id', common_1.ParseUUIDPipe)),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], SessionsController.prototype, "revertSession", null);
__decorate([
    (0, common_1.Get)(':id/input-file-changes'),
    (0, swagger_1.ApiOperation)({
        summary: 'Get file changes for specific inputs in a session',
    }),
    (0, swagger_1.ApiParam)({ name: 'id', description: 'Session UUID', format: 'uuid' }),
    (0, swagger_1.ApiQuery)({
        name: 'inputIds',
        required: true,
        description: 'Comma-separated list of input UUIDs',
    }),
    (0, swagger_1.ApiResponse)({
        status: 200,
        description: 'List of file changes for the specified inputs',
        schema: {
            type: 'array',
            items: {
                type: 'object',
                properties: {
                    file_path: { type: 'string' },
                    initial_content: { type: 'string', nullable: true },
                    current_content: { type: 'string', nullable: true },
                },
            },
        },
    }),
    (0, swagger_1.ApiResponse)({ status: 404, description: 'Session or input not found' }),
    __param(0, (0, common_1.Param)('id', common_1.ParseUUIDPipe)),
    __param(1, (0, common_1.Query)('inputIds')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String]),
    __metadata("design:returntype", Promise)
], SessionsController.prototype, "getInputFileChanges", null);
__decorate([
    (0, common_1.Post)(':id/revert-input-file-changes'),
    (0, common_1.HttpCode)(common_1.HttpStatus.OK),
    (0, swagger_1.ApiOperation)({
        summary: 'Revert file changes for specific inputs in a session',
    }),
    (0, swagger_1.ApiParam)({ name: 'id', description: 'Session UUID', format: 'uuid' }),
    (0, swagger_1.ApiBody)({
        schema: {
            type: 'object',
            properties: {
                input_ids: {
                    type: 'array',
                    items: { type: 'string', format: 'uuid' },
                },
            },
            required: ['input_ids'],
        },
    }),
    (0, swagger_1.ApiResponse)({
        status: 200,
        description: 'Input file changes reverted',
        type: session_dto_1.RevertSessionResponseDto,
    }),
    (0, swagger_1.ApiResponse)({ status: 404, description: 'Session or input not found' }),
    __param(0, (0, common_1.Param)('id', common_1.ParseUUIDPipe)),
    __param(1, (0, common_1.Body)('input_ids')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Array]),
    __metadata("design:returntype", Promise)
], SessionsController.prototype, "revertInputFileChanges", null);
exports.SessionsController = SessionsController = __decorate([
    (0, swagger_1.ApiTags)('sessions'),
    (0, common_1.Controller)('sessions'),
    __metadata("design:paramtypes", [sessions_service_1.SessionsService,
        session_transfer_service_1.SessionTransferService,
        session_followup_service_1.SessionFollowupService])
], SessionsController);
//# sourceMappingURL=sessions.controller.js.map