"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uploadCustomAIBundle = void 0;
const drizzle_orm_1 = require("drizzle-orm");
const database_1 = require("../../../database");
const tables_1 = require("../../../database/tables");
const logger_1 = __importDefault(require("../../../logger"));
const customAIApplicationUpload_1 = require("../../middlewares/customAIApplicationUpload");
const customAIApplicationService_1 = require("../../services/customAIApplicationService");
const uploadCustomAIBundle = async (req, res) => {
    const zipPath = req.file?.path;
    try {
        const { applicationId } = req.params;
        if (!applicationId) {
            res.status(400).json({ success: false, message: 'applicationId is required' });
            return;
        }
        if (!req.file) {
            res.status(400).json({ success: false, message: 'zipFile is required' });
            return;
        }
        const db = await (0, database_1.getDb)();
        const [application] = await db
            .select({
            id: tables_1.applicationsTable.id,
            projectId: tables_1.applicationsTable.projectId,
            workspaceId: tables_1.applicationsTable.workspaceId,
        })
            .from(tables_1.applicationsTable)
            .where((0, drizzle_orm_1.eq)(tables_1.applicationsTable.id, applicationId))
            .limit(1);
        if (!application) {
            res.status(404).json({ success: false, message: 'Application not found' });
            return;
        }
        const service = new customAIApplicationService_1.CustomAIApplicationService();
        const { language, applicationPath, envVariables, removedEnvKeys, transformResponse } = customAIApplicationService_1.CustomAIApplicationService.parseRequestFields(req.body);
        if (!language) {
            res.status(400).json({ success: false, message: 'language must be python, js, or go' });
            return;
        }
        if (!applicationPath) {
            res.status(400).json({ success: false, message: 'applicationPath is required' });
            return;
        }
        // Pass through the client auth header as-is (e.g. "Bearer <jwt>") — Control Plane /upload expects that format.
        const accessToken = (req.headers['x-access-token'] || req.headers.authorization);
        const tokenValue = Array.isArray(accessToken) ? accessToken[0] : accessToken;
        if (!tokenValue || String(tokenValue).trim() === '') {
            res.status(401).json({ success: false, message: 'Authentication token is required' });
            return;
        }
        const orgId = String(req.body.orgId ?? application.workspaceId ?? '').trim();
        const projectId = String(req.body.projectId ?? application.projectId ?? '').trim();
        if (!orgId || !projectId) {
            res.status(400).json({ success: false, message: 'orgId and projectId are required' });
            return;
        }
        const provider = await service.uploadBundleAndUpdateApplication({
            applicationId,
            projectId,
            orgId,
            zipFilePath: zipPath,
            zipFileName: req.file.originalname || 'bundle.zip',
            language,
            applicationPath,
            setupMethod: 'upload',
            transformResponse,
            envVariables,
            removedEnvKeys,
            accessToken: String(tokenValue).trim(),
        });
        res.json({
            success: true,
            data: { provider },
            message: 'Custom AI bundle uploaded successfully',
        });
    }
    catch (error) {
        logger_1.default.error(`uploadCustomAIBundle failed: ${error}`);
        const message = error instanceof Error ? error.message : 'Failed to upload custom AI bundle';
        const status = /unauthorized/i.test(message) ? 401 : 400;
        res.status(status).json({
            success: false,
            message: status === 401
                ? 'Bundle upload to storage was unauthorized. Ensure you are signed in and Control Plane upload is configured.'
                : message,
        });
    }
    finally {
        (0, customAIApplicationUpload_1.cleanupCustomAIUploadFile)(zipPath);
    }
};
exports.uploadCustomAIBundle = uploadCustomAIBundle;
//# sourceMappingURL=upload-custom-ai-bundle.js.map