"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateShareableReport = void 0;
const drizzle_orm_1 = require("drizzle-orm");
const database_1 = require("../../../database");
const tables_1 = require("../../../database/tables");
const hasOwn = Object.prototype.hasOwnProperty;
const updateShareableReport = async (req, res) => {
    try {
        const { testRunId } = req.params;
        if (!testRunId) {
            return res.status(400).json({ error: 'Missing testRunId parameter' });
        }
        const { shareableReportExpiry, shareableReportAccessKey, } = req.body ?? {};
        const updatePayload = {};
        if (hasOwn.call(req.body ?? {}, 'shareableReportExpiry')) {
            if (shareableReportExpiry === null || shareableReportExpiry === '') {
                updatePayload.shareableReportExpiry = null;
            }
            else {
                const parsedExpiry = new Date(shareableReportExpiry);
                if (Number.isNaN(parsedExpiry.getTime())) {
                    return res
                        .status(400)
                        .json({ error: 'shareableReportExpiry must be a valid date when provided.' });
                }
                updatePayload.shareableReportExpiry = parsedExpiry;
            }
        }
        if (hasOwn.call(req.body ?? {}, 'shareableReportAccessKey')) {
            if (shareableReportAccessKey !== null && typeof shareableReportAccessKey !== 'string') {
                return res
                    .status(400)
                    .json({ error: 'shareableReportAccessKey must be a string or null when provided.' });
            }
            updatePayload.shareableReportAccessKey = shareableReportAccessKey ?? null;
        }
        if (Object.keys(updatePayload).length === 0) {
            return res.status(400).json({ error: 'No valid fields provided for update.' });
        }
        const db = await (0, database_1.getDb)();
        const [updatedTestRun] = await db
            .update(tables_1.testRunsTable)
            .set(updatePayload)
            .where((0, drizzle_orm_1.eq)(tables_1.testRunsTable.id, testRunId))
            .returning({
            id: tables_1.testRunsTable.id,
            shareableReportExpiry: tables_1.testRunsTable.shareableReportExpiry,
            shareableReportAccessKey: tables_1.testRunsTable.shareableReportAccessKey,
        });
        if (!updatedTestRun) {
            return res.status(404).json({ error: 'Test run not found.' });
        }
        return res.status(200).json({ status: 'success', data: updatedTestRun });
    }
    catch (error) {
        console.error('Failed to update shareable report fields', error);
        return res.status(500).json({ error: 'Failed to update shareable report fields.' });
    }
};
exports.updateShareableReport = updateShareableReport;
//# sourceMappingURL=update-shareable-report.js.map