"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.setupPlanBoard = setupPlanBoard;
exports.fetchPlanItems = fetchPlanItems;
exports.fetchPlanItemsWithLatestSourceWorks = fetchPlanItemsWithLatestSourceWorks;
exports.createPlanItem = createPlanItem;
exports.updatePlanItem = updatePlanItem;
exports.updatePlanItemJangsingProcessingRequired = updatePlanItemJangsingProcessingRequired;
exports.deletePlanItem = deletePlanItem;
exports.runPlanAction = runPlanAction;
exports.fetchPlanIssueHistories = fetchPlanIssueHistories;
exports.appendPlanIssueAction = appendPlanIssueAction;
exports.fetchPlanActionHistories = fetchPlanActionHistories;
exports.appendPlanActionHistory = appendPlanActionHistory;
exports.fetchPlanSourceWorkHistories = fetchPlanSourceWorkHistories;
exports.fetchReleaseReviewBoardItems = fetchReleaseReviewBoardItems;
exports.updatePlanReleaseReview = updatePlanReleaseReview;
exports.fetchPlanSourceWorkHistory = fetchPlanSourceWorkHistory;
exports.fetchPlanScheduledTasks = fetchPlanScheduledTasks;
exports.createPlanScheduledTask = createPlanScheduledTask;
exports.updatePlanScheduledTask = updatePlanScheduledTask;
exports.deletePlanScheduledTask = deletePlanScheduledTask;
var clientIdentity_1 = require("../../app/main/clientIdentity");
var automationTypeAccess_1 = require("../../app/main/automationTypeAccess");
var tokenAccess_1 = require("../../app/main/tokenAccess");
function resolvePlanApiBaseUrl() {
    if (import.meta.env.VITE_WORK_SERVER_URL) {
        return import.meta.env.VITE_WORK_SERVER_URL;
    }
    return '/api';
}
function normalizePlanAutomationType(value) {
    return (0, automationTypeAccess_1.normalizeAutomationTypeId)(value);
}
function resolveWorkServerFallbackBaseUrl() {
    if (typeof window === 'undefined') {
        return null;
    }
    var hostname = window.location.hostname;
    var isLocalWorkServerHost = hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '0.0.0.0';
    if (!isLocalWorkServerHost) {
        return null;
    }
    var fallbackUrl = new URL(window.location.origin);
    fallbackUrl.port = '3100';
    fallbackUrl.pathname = '/api';
    fallbackUrl.search = '';
    fallbackUrl.hash = '';
    return fallbackUrl.toString().replace(/\/+$/, '');
}
var PLAN_API_BASE_URL = resolvePlanApiBaseUrl();
var PLAN_API_FALLBACK_BASE_URL = !import.meta.env.VITE_WORK_SERVER_URL && PLAN_API_BASE_URL === '/api'
    ? resolveWorkServerFallbackBaseUrl()
    : null;
var PlanApiError = /** @class */ (function (_super) {
    __extends(PlanApiError, _super);
    function PlanApiError(message, status) {
        var _this = _super.call(this, message) || this;
        _this.name = 'PlanApiError';
        _this.status = status;
        return _this;
    }
    return PlanApiError;
}(Error));
function requestOnce(baseUrl, path, init) {
    return __awaiter(this, void 0, void 0, function () {
        var headers, hasBody, method, timeoutMs, controller, timeoutId, token, response, error_1, text, payload, contentType, text;
        var _a, _b, _c, _d;
        return __generator(this, function (_e) {
            switch (_e.label) {
                case 0:
                    headers = (0, clientIdentity_1.appendClientIdHeader)(init === null || init === void 0 ? void 0 : init.headers);
                    hasBody = (init === null || init === void 0 ? void 0 : init.body) !== undefined && init.body !== null;
                    method = (_b = (_a = init === null || init === void 0 ? void 0 : init.method) === null || _a === void 0 ? void 0 : _a.toUpperCase()) !== null && _b !== void 0 ? _b : 'GET';
                    timeoutMs = 8000;
                    controller = new AbortController();
                    timeoutId = setTimeout(function () {
                        controller.abort();
                    }, timeoutMs);
                    if (hasBody && !headers.has('Content-Type')) {
                        headers.set('Content-Type', 'application/json');
                    }
                    token = (0, tokenAccess_1.getRegisteredAccessToken)();
                    if (token && !headers.has('X-Access-Token')) {
                        headers.set('X-Access-Token', token);
                    }
                    _e.label = 1;
                case 1:
                    _e.trys.push([1, 3, , 4]);
                    return [4 /*yield*/, fetch("".concat(baseUrl).concat(path), __assign(__assign({}, init), { headers: headers, signal: controller.signal, cache: (_c = init === null || init === void 0 ? void 0 : init.cache) !== null && _c !== void 0 ? _c : (method === 'GET' ? 'no-store' : undefined) }))];
                case 2:
                    response = _e.sent();
                    return [3 /*break*/, 4];
                case 3:
                    error_1 = _e.sent();
                    clearTimeout(timeoutId);
                    if (error_1 instanceof DOMException && error_1.name === 'AbortError') {
                        throw new PlanApiError('서버 응답이 지연됩니다. 잠시 후 다시 시도해 주세요.', 408);
                    }
                    throw error_1;
                case 4:
                    clearTimeout(timeoutId);
                    if (!!response.ok) return [3 /*break*/, 6];
                    return [4 /*yield*/, response.text()];
                case 5:
                    text = _e.sent();
                    try {
                        payload = JSON.parse(text);
                        throw new PlanApiError(payload.message || "요청 처리에 실패했습니다.", response.status);
                    }
                    catch (_f) {
                        throw new PlanApiError(text || "요청 처리에 실패했습니다.", response.status);
                    }
                    _e.label = 6;
                case 6:
                    contentType = (_d = response.headers.get("content-type")) !== null && _d !== void 0 ? _d : "";
                    if (!!contentType.toLowerCase().includes("application/json")) return [3 /*break*/, 8];
                    return [4 /*yield*/, response.text()];
                case 7:
                    text = _e.sent();
                    throw new PlanApiError(text ? "서버 응답이 JSON이 아닙니다." : "서버 응답을 확인할 수 없습니다.", 502);
                case 8: return [2 /*return*/, response.json()];
            }
        });
    });
}
function request(path, init) {
    return __awaiter(this, void 0, void 0, function () {
        var error_2, shouldRetryWithFallback;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 2, , 3]);
                    return [4 /*yield*/, requestOnce(PLAN_API_BASE_URL, path, init)];
                case 1: return [2 /*return*/, _a.sent()];
                case 2:
                    error_2 = _a.sent();
                    shouldRetryWithFallback = PLAN_API_FALLBACK_BASE_URL &&
                        PLAN_API_FALLBACK_BASE_URL !== PLAN_API_BASE_URL &&
                        (error_2 instanceof PlanApiError
                            ? error_2.status === 404 || error_2.status === 408 || error_2.status === 502
                            : error_2 instanceof Error && (/not found/i.test(error_2.message) || /404/.test(error_2.message)));
                    if (!shouldRetryWithFallback) {
                        throw error_2;
                    }
                    return [2 /*return*/, requestOnce(PLAN_API_FALLBACK_BASE_URL, path, init)];
                case 3: return [2 /*return*/];
            }
        });
    });
}
function requestWithMetaOnce(baseUrl, path, init) {
    return __awaiter(this, void 0, void 0, function () {
        var headers, hasBody, method, timeoutMs, controller, timeoutId, token, startedAt, response, error_3, text, meta, payload, contentType;
        var _a, _b, _c, _d;
        return __generator(this, function (_e) {
            switch (_e.label) {
                case 0:
                    headers = (0, clientIdentity_1.appendClientIdHeader)(init === null || init === void 0 ? void 0 : init.headers);
                    hasBody = (init === null || init === void 0 ? void 0 : init.body) !== undefined && init.body !== null;
                    method = (_b = (_a = init === null || init === void 0 ? void 0 : init.method) === null || _a === void 0 ? void 0 : _a.toUpperCase()) !== null && _b !== void 0 ? _b : 'GET';
                    timeoutMs = 8000;
                    controller = new AbortController();
                    timeoutId = setTimeout(function () {
                        controller.abort();
                    }, timeoutMs);
                    if (hasBody && !headers.has('Content-Type')) {
                        headers.set('Content-Type', 'application/json');
                    }
                    token = (0, tokenAccess_1.getRegisteredAccessToken)();
                    if (token && !headers.has('X-Access-Token')) {
                        headers.set('X-Access-Token', token);
                    }
                    startedAt = performance.now();
                    _e.label = 1;
                case 1:
                    _e.trys.push([1, 3, , 4]);
                    return [4 /*yield*/, fetch("".concat(baseUrl).concat(path), __assign(__assign({}, init), { headers: headers, signal: controller.signal, cache: (_c = init === null || init === void 0 ? void 0 : init.cache) !== null && _c !== void 0 ? _c : (method === 'GET' ? 'no-store' : undefined) }))];
                case 2:
                    response = _e.sent();
                    return [3 /*break*/, 4];
                case 3:
                    error_3 = _e.sent();
                    clearTimeout(timeoutId);
                    if (error_3 instanceof DOMException && error_3.name === 'AbortError') {
                        throw new PlanApiError('서버 응답이 지연됩니다. 잠시 후 다시 시도해 주세요.', 408);
                    }
                    throw error_3;
                case 4:
                    clearTimeout(timeoutId);
                    return [4 /*yield*/, response.text()];
                case 5:
                    text = _e.sent();
                    meta = {
                        durationMs: Math.max(0, Math.round(performance.now() - startedAt)),
                        responseBytes: new TextEncoder().encode(text).length,
                    };
                    if (!response.ok) {
                        try {
                            payload = JSON.parse(text);
                            throw new PlanApiError(payload.message || '요청 처리에 실패했습니다.', response.status);
                        }
                        catch (_f) {
                            throw new PlanApiError(text || '요청 처리에 실패했습니다.', response.status);
                        }
                    }
                    contentType = (_d = response.headers.get('content-type')) !== null && _d !== void 0 ? _d : '';
                    if (!contentType.toLowerCase().includes('application/json')) {
                        throw new PlanApiError(text ? '서버 응답이 JSON이 아닙니다.' : '서버 응답을 확인할 수 없습니다.', 502);
                    }
                    return [2 /*return*/, {
                            data: JSON.parse(text),
                            meta: meta,
                        }];
            }
        });
    });
}
function requestWithMeta(path, init) {
    return __awaiter(this, void 0, void 0, function () {
        var error_4, shouldRetryWithFallback;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 2, , 3]);
                    return [4 /*yield*/, requestWithMetaOnce(PLAN_API_BASE_URL, path, init)];
                case 1: return [2 /*return*/, _a.sent()];
                case 2:
                    error_4 = _a.sent();
                    shouldRetryWithFallback = PLAN_API_FALLBACK_BASE_URL &&
                        PLAN_API_FALLBACK_BASE_URL !== PLAN_API_BASE_URL &&
                        (error_4 instanceof PlanApiError
                            ? error_4.status === 404 || error_4.status === 408 || error_4.status === 502
                            : error_4 instanceof Error && (/not found/i.test(error_4.message) || /404/.test(error_4.message)));
                    if (!shouldRetryWithFallback) {
                        throw error_4;
                    }
                    return [2 /*return*/, requestWithMetaOnce(PLAN_API_FALLBACK_BASE_URL, path, init)];
                case 3: return [2 /*return*/];
            }
        });
    });
}
function setupPlanBoard() {
    return __awaiter(this, void 0, void 0, function () {
        return __generator(this, function (_a) {
            return [2 /*return*/, request('/plan/setup', {
                    method: 'POST',
                    body: JSON.stringify({}),
                })];
        });
    });
}
function fetchPlanItems(status) {
    return __awaiter(this, void 0, void 0, function () {
        var query, response;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    void status;
                    query = '';
                    return [4 /*yield*/, request("/plan/items".concat(query))];
                case 1:
                    response = _a.sent();
                    return [2 /*return*/, response.items.map(normalizePlanItem)];
            }
        });
    });
}
function fetchPlanItemsWithLatestSourceWorks(status) {
    return __awaiter(this, void 0, void 0, function () {
        var query, response;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    void status;
                    query = '';
                    return [4 /*yield*/, requestWithMeta("/plan/items".concat(query))];
                case 1:
                    response = _a.sent();
                    return [2 /*return*/, {
                            items: response.data.items.map(normalizePlanItem),
                            meta: response.meta,
                        }];
            }
        });
    });
}
function createPlanItem(draft) {
    return __awaiter(this, void 0, void 0, function () {
        var response;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, request('/plan/items', {
                        method: 'POST',
                        body: JSON.stringify({
                            workId: draft.workId,
                            note: draft.note,
                            automationType: draft.automationType,
                            automationContextIds: draft.automationContextIds,
                            jangsingProcessingRequired: draft.jangsingProcessingRequired,
                            autoDeployToMain: draft.autoDeployToMain,
                            suppressWebPush: draft.suppressWebPush,
                        }),
                    })];
                case 1:
                    response = _a.sent();
                    return [2 /*return*/, normalizePlanItem(response.item)];
            }
        });
    });
}
function updatePlanItem(draft) {
    return __awaiter(this, void 0, void 0, function () {
        var response;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!draft.id) {
                        throw new Error('수정할 작업 항목 ID가 없습니다.');
                    }
                    return [4 /*yield*/, request("/plan/items/".concat(draft.id), {
                            method: 'PATCH',
                            body: JSON.stringify({
                                workId: draft.workId,
                                note: draft.note,
                                automationType: draft.automationType,
                                automationContextIds: draft.automationContextIds,
                                jangsingProcessingRequired: draft.jangsingProcessingRequired,
                                autoDeployToMain: draft.autoDeployToMain,
                                suppressWebPush: draft.suppressWebPush,
                            }),
                        })];
                case 1:
                    response = _a.sent();
                    return [2 /*return*/, normalizePlanItem(response.item)];
            }
        });
    });
}
function updatePlanItemJangsingProcessingRequired(id, jangsingProcessingRequired) {
    return __awaiter(this, void 0, void 0, function () {
        var response;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, request("/plan/items/".concat(id), {
                        method: 'PATCH',
                        body: JSON.stringify({
                            jangsingProcessingRequired: jangsingProcessingRequired,
                        }),
                    })];
                case 1:
                    response = _a.sent();
                    return [2 /*return*/, normalizePlanItem(response.item)];
            }
        });
    });
}
function deletePlanItem(id) {
    return __awaiter(this, void 0, void 0, function () {
        var response;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, request("/plan/items/".concat(id), {
                        method: 'DELETE',
                    })];
                case 1:
                    response = _a.sent();
                    return [2 /*return*/, response.id];
            }
        });
    });
}
function runPlanAction(id, action) {
    return __awaiter(this, void 0, void 0, function () {
        var response;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, request("/plan/items/".concat(id, "/actions/").concat(action), {
                        method: 'POST',
                        body: JSON.stringify({}),
                    })];
                case 1:
                    response = _a.sent();
                    return [2 /*return*/, {
                            item: normalizePlanItem(response.item),
                            message: response.message,
                        }];
            }
        });
    });
}
function fetchPlanIssueHistories(id) {
    return __awaiter(this, void 0, void 0, function () {
        var response;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, request("/plan/items/".concat(id, "/issues"))];
                case 1:
                    response = _a.sent();
                    return [2 /*return*/, response.items];
            }
        });
    });
}
function appendPlanIssueAction(id_1, actionNote_1) {
    return __awaiter(this, arguments, void 0, function (id, actionNote, resolve, retry) {
        var response;
        if (resolve === void 0) { resolve = false; }
        if (retry === void 0) { retry = false; }
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, request("/plan/items/".concat(id, "/issues/action"), {
                        method: 'POST',
                        body: JSON.stringify({
                            actionNote: actionNote,
                            resolve: resolve,
                            retry: retry,
                        }),
                    })];
                case 1:
                    response = _a.sent();
                    return [2 /*return*/, {
                            item: response.item,
                            planItem: response.planItem ? normalizePlanItem(response.planItem) : undefined,
                            message: response.message,
                        }];
            }
        });
    });
}
function fetchPlanActionHistories(id) {
    return __awaiter(this, void 0, void 0, function () {
        var response;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, request("/plan/items/".concat(id, "/actions"))];
                case 1:
                    response = _a.sent();
                    return [2 /*return*/, response.items];
            }
        });
    });
}
function appendPlanActionHistory(id, actionNote) {
    return __awaiter(this, void 0, void 0, function () {
        var response;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, request("/plan/items/".concat(id, "/actions/note"), {
                        method: 'POST',
                        body: JSON.stringify({
                            actionNote: actionNote,
                            actionType: '추가조치',
                        }),
                    })];
                case 1:
                    response = _a.sent();
                    return [2 /*return*/, {
                            item: response.item,
                            planItem: response.planItem ? normalizePlanItem(response.planItem) : undefined,
                            message: response.message,
                        }];
            }
        });
    });
}
function normalizePlanItem(item) {
    return __assign(__assign({}, item), { automationType: normalizePlanAutomationType(item.automationType), automationBehaviorType: (0, automationTypeAccess_1.normalizeAutomationTypeId)(item.automationBehaviorType), automationContextIds: Array.isArray(item.automationContextIds)
            ? item.automationContextIds.map(function (value) { return String(value).trim(); }).filter(Boolean)
            : [], releaseReviewNote: typeof item.releaseReviewNote === 'string' ? item.releaseReviewNote : '', usageSnapshot: normalizePlanAutomationUsageSnapshot(item.usageSnapshot) });
}
function normalizePlanAutomationUsageSnapshot(value) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
    if (!value) {
        return null;
    }
    return {
        tokenTotals: {
            total: Number((_b = (_a = value.tokenTotals) === null || _a === void 0 ? void 0 : _a.total) !== null && _b !== void 0 ? _b : 0),
            input: Number((_d = (_c = value.tokenTotals) === null || _c === void 0 ? void 0 : _c.input) !== null && _d !== void 0 ? _d : 0),
            output: Number((_f = (_e = value.tokenTotals) === null || _e === void 0 ? void 0 : _e.output) !== null && _f !== void 0 ? _f : 0),
            cached: Number((_h = (_g = value.tokenTotals) === null || _g === void 0 ? void 0 : _g.cached) !== null && _h !== void 0 ? _h : 0),
            reasoning: Number((_k = (_j = value.tokenTotals) === null || _j === void 0 ? void 0 : _j.reasoning) !== null && _k !== void 0 ? _k : 0),
        },
        totalTokens: Number((_l = value.totalTokens) !== null && _l !== void 0 ? _l : 0),
        retryCount: Number((_m = value.retryCount) !== null && _m !== void 0 ? _m : 0),
        sourceWorkCount: Number((_o = value.sourceWorkCount) !== null && _o !== void 0 ? _o : 0),
        processingStartedAt: (_p = value.processingStartedAt) !== null && _p !== void 0 ? _p : null,
        processingEndedAt: (_q = value.processingEndedAt) !== null && _q !== void 0 ? _q : null,
        processingEndedAtSource: (_r = value.processingEndedAtSource) !== null && _r !== void 0 ? _r : null,
        processingDurationSeconds: value.processingDurationSeconds === null || value.processingDurationSeconds === undefined
            ? null
            : Number(value.processingDurationSeconds),
    };
}
function normalizePlanScheduledTaskDateRanges(value) {
    if (!Array.isArray(value)) {
        return [];
    }
    return value
        .map(function (item) { return ({
        startDate: typeof (item === null || item === void 0 ? void 0 : item.startDate) === 'string' ? item.startDate.trim() : '',
        endDate: typeof (item === null || item === void 0 ? void 0 : item.endDate) === 'string' ? item.endDate.trim() : '',
    }); })
        .filter(function (item) { return item.startDate && item.endDate; });
}
function normalizePlanScheduledTaskWeekdays(value) {
    if (!Array.isArray(value)) {
        return [];
    }
    return Array.from(new Set(value
        .map(function (item) { return Number(item); })
        .filter(function (item) { return Number.isInteger(item) && item >= 0 && item <= 6; }))).sort(function (left, right) { return left - right; });
}
function normalizePlanScheduledTaskTimeWindows(value) {
    if (!Array.isArray(value)) {
        return [];
    }
    return value
        .map(function (item) { return ({
        startTime: typeof (item === null || item === void 0 ? void 0 : item.startTime) === 'string' && /^([01]\d|2[0-3]):[0-5]\d$/.test(item.startTime.trim())
            ? item.startTime.trim()
            : null,
        endTime: typeof (item === null || item === void 0 ? void 0 : item.endTime) === 'string' && /^([01]\d|2[0-3]):[0-5]\d$/.test(item.endTime.trim())
            ? item.endTime.trim()
            : null,
    }); })
        .filter(function (item) { return item.startTime || item.endTime; });
}
function fetchPlanSourceWorkHistories(id) {
    return __awaiter(this, void 0, void 0, function () {
        var response;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, request("/plan/items/".concat(id, "/source-works"))];
                case 1:
                    response = _a.sent();
                    return [2 /*return*/, response.items];
            }
        });
    });
}
function fetchReleaseReviewBoardItems() {
    return __awaiter(this, void 0, void 0, function () {
        var response;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, request('/plan/release-reviews')];
                case 1:
                    response = _a.sent();
                    return [2 /*return*/, response.items];
            }
        });
    });
}
function updatePlanReleaseReview(planItemId, payload) {
    return __awaiter(this, void 0, void 0, function () {
        var response;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, request("/plan/release-reviews/".concat(planItemId), {
                        method: 'PATCH',
                        body: JSON.stringify(payload),
                    })];
                case 1:
                    response = _a.sent();
                    return [2 /*return*/, response.item];
            }
        });
    });
}
function fetchPlanSourceWorkHistory(id, sourceWorkId) {
    return __awaiter(this, void 0, void 0, function () {
        var response;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, request("/plan/items/".concat(id, "/source-works/").concat(sourceWorkId))];
                case 1:
                    response = _a.sent();
                    return [2 /*return*/, response.item];
            }
        });
    });
}
function requestPlanScheduleTask() {
    return __awaiter(this, arguments, void 0, function (pathSuffix, init) {
        var paths, lastNotFoundError, _i, paths_1, path, error_5;
        if (pathSuffix === void 0) { pathSuffix = ''; }
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    paths = [
                        "/plan/scheduled-tasks".concat(pathSuffix),
                        "/plan/schedule/tasks".concat(pathSuffix),
                        "/plan/schedule".concat(pathSuffix),
                        "/plan/schedules".concat(pathSuffix),
                        "/plans/scheduled-tasks".concat(pathSuffix),
                        "/plans/schedule/tasks".concat(pathSuffix),
                        "/plans/schedule".concat(pathSuffix),
                        "/plans/schedules".concat(pathSuffix),
                    ];
                    lastNotFoundError = null;
                    _i = 0, paths_1 = paths;
                    _a.label = 1;
                case 1:
                    if (!(_i < paths_1.length)) return [3 /*break*/, 6];
                    path = paths_1[_i];
                    _a.label = 2;
                case 2:
                    _a.trys.push([2, 4, , 5]);
                    return [4 /*yield*/, request(path, init)];
                case 3: return [2 /*return*/, _a.sent()];
                case 4:
                    error_5 = _a.sent();
                    if (error_5 instanceof PlanApiError && error_5.status === 404) {
                        lastNotFoundError = error_5;
                        return [3 /*break*/, 5];
                    }
                    throw error_5;
                case 5:
                    _i++;
                    return [3 /*break*/, 1];
                case 6: throw lastNotFoundError !== null && lastNotFoundError !== void 0 ? lastNotFoundError : new PlanApiError('스케줄 API 경로를 찾을 수 없습니다.', 404);
            }
        });
    });
}
function fetchPlanScheduledTasks() {
    return __awaiter(this, void 0, void 0, function () {
        var response;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, requestPlanScheduleTask()];
                case 1:
                    response = _a.sent();
                    return [2 /*return*/, response.items.map(function (item) { return (__assign(__assign({}, item), { automationType: normalizePlanAutomationType(item.automationType), automationContextIds: Array.isArray(item.automationContextIds)
                                ? item.automationContextIds.map(function (value) { return String(value).trim(); }).filter(Boolean)
                                : [], scheduleWeekdays: normalizePlanScheduledTaskWeekdays(item.scheduleWeekdays), scheduleDateRanges: normalizePlanScheduledTaskDateRanges(item.scheduleDateRanges), repeatWindows: normalizePlanScheduledTaskTimeWindows(item.repeatWindows), refreshContextSnapshotOnNextRun: Boolean(item.refreshContextSnapshotOnNextRun), recreateManagedServiceOnNextSave: Boolean(item.recreateManagedServiceOnNextSave) })); })];
            }
        });
    });
}
function createPlanScheduledTask(draft) {
    return __awaiter(this, void 0, void 0, function () {
        var response;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, requestPlanScheduleTask('', {
                        method: 'POST',
                        body: JSON.stringify({
                            workId: draft.workId,
                            note: draft.note,
                            automationType: draft.automationType,
                            automationContextIds: draft.automationContextIds,
                            releaseTarget: draft.releaseTarget,
                            jangsingProcessingRequired: draft.jangsingProcessingRequired,
                            autoDeployToMain: draft.autoDeployToMain,
                            suppressWebPush: draft.suppressWebPush,
                            enabled: draft.enabled,
                            immediateRunEnabled: draft.immediateRunEnabled,
                            refreshContextSnapshotOnNextRun: draft.refreshContextSnapshotOnNextRun,
                            executionMode: draft.executionMode,
                            recreateManagedServiceOnNextSave: draft.recreateManagedServiceOnNextSave,
                            scheduleMode: draft.scheduleMode,
                            repeatIntervalValue: draft.repeatIntervalValue,
                            repeatIntervalUnit: draft.repeatIntervalUnit,
                            repeatIntervalSeconds: draft.repeatIntervalSeconds,
                            repeatIntervalMinutes: draft.repeatIntervalMinutes,
                            dailyRunTime: draft.dailyRunTime,
                            scheduleWeekdays: draft.scheduleWeekdays,
                            scheduleDateRanges: draft.scheduleDateRanges,
                            repeatWindows: draft.repeatWindows,
                            repeatWindowStartTime: draft.repeatWindowStartTime,
                            repeatWindowEndTime: draft.repeatWindowEndTime,
                        }),
                    })];
                case 1:
                    response = _a.sent();
                    return [2 /*return*/, {
                            item: __assign(__assign({}, response.item), { automationType: normalizePlanAutomationType(response.item.automationType), automationContextIds: Array.isArray(response.item.automationContextIds)
                                    ? response.item.automationContextIds.map(function (value) { return String(value).trim(); }).filter(Boolean)
                                    : [], scheduleWeekdays: normalizePlanScheduledTaskWeekdays(response.item.scheduleWeekdays), scheduleDateRanges: normalizePlanScheduledTaskDateRanges(response.item.scheduleDateRanges), repeatWindows: normalizePlanScheduledTaskTimeWindows(response.item.repeatWindows), refreshContextSnapshotOnNextRun: Boolean(response.item.refreshContextSnapshotOnNextRun), recreateManagedServiceOnNextSave: Boolean(response.item.recreateManagedServiceOnNextSave) }),
                            registeredPlan: response.registeredPlan,
                            registeredBoardPosts: Array.isArray(response.registeredBoardPosts) ? response.registeredBoardPosts : [],
                        }];
            }
        });
    });
}
function updatePlanScheduledTask(draft) {
    return __awaiter(this, void 0, void 0, function () {
        var response;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!draft.id) {
                        throw new Error('수정할 스케줄 ID가 없습니다.');
                    }
                    return [4 /*yield*/, requestPlanScheduleTask("/".concat(draft.id), {
                            method: 'PATCH',
                            body: JSON.stringify({
                                workId: draft.workId,
                                note: draft.note,
                                automationType: draft.automationType,
                                automationContextIds: draft.automationContextIds,
                                releaseTarget: draft.releaseTarget,
                                jangsingProcessingRequired: draft.jangsingProcessingRequired,
                                autoDeployToMain: draft.autoDeployToMain,
                                suppressWebPush: draft.suppressWebPush,
                                enabled: draft.enabled,
                                immediateRunEnabled: draft.immediateRunEnabled,
                                refreshContextSnapshotOnNextRun: draft.refreshContextSnapshotOnNextRun,
                                executionMode: draft.executionMode,
                                recreateManagedServiceOnNextSave: draft.recreateManagedServiceOnNextSave,
                                scheduleMode: draft.scheduleMode,
                                repeatIntervalValue: draft.repeatIntervalValue,
                                repeatIntervalUnit: draft.repeatIntervalUnit,
                                repeatIntervalSeconds: draft.repeatIntervalSeconds,
                                repeatIntervalMinutes: draft.repeatIntervalMinutes,
                                dailyRunTime: draft.dailyRunTime,
                                scheduleWeekdays: draft.scheduleWeekdays,
                                scheduleDateRanges: draft.scheduleDateRanges,
                                repeatWindows: draft.repeatWindows,
                                repeatWindowStartTime: draft.repeatWindowStartTime,
                                repeatWindowEndTime: draft.repeatWindowEndTime,
                            }),
                        })];
                case 1:
                    response = _a.sent();
                    return [2 /*return*/, {
                            item: __assign(__assign({}, response.item), { automationType: normalizePlanAutomationType(response.item.automationType), automationContextIds: Array.isArray(response.item.automationContextIds)
                                    ? response.item.automationContextIds.map(function (value) { return String(value).trim(); }).filter(Boolean)
                                    : [], scheduleWeekdays: normalizePlanScheduledTaskWeekdays(response.item.scheduleWeekdays), scheduleDateRanges: normalizePlanScheduledTaskDateRanges(response.item.scheduleDateRanges), repeatWindows: normalizePlanScheduledTaskTimeWindows(response.item.repeatWindows), refreshContextSnapshotOnNextRun: Boolean(response.item.refreshContextSnapshotOnNextRun), recreateManagedServiceOnNextSave: Boolean(response.item.recreateManagedServiceOnNextSave) }),
                            registeredPlan: response.registeredPlan,
                            registeredBoardPosts: Array.isArray(response.registeredBoardPosts) ? response.registeredBoardPosts : [],
                        }];
            }
        });
    });
}
function deletePlanScheduledTask(id) {
    return __awaiter(this, void 0, void 0, function () {
        var response;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, requestPlanScheduleTask("/".concat(id), {
                        method: 'DELETE',
                    })];
                case 1:
                    response = _a.sent();
                    return [2 /*return*/, response.id];
            }
        });
    });
}
