"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.applySpecRegistryUnlink = applySpecRegistryUnlink;
const cli_constants_1 = require("../config/cli-constants");
const document_io_1 = require("./document-io");
const traceability_1 = require("./traceability");
function applySpecRegistryUnlink(input) {
    const entryId = readEntryId(input.entryId);
    const targetIndex = input.currentDocument.entries.findIndex((entry) => entry.id === entryId);
    if (targetIndex === -1) {
        return {
            ok: false,
            findings: [
                createFinding("SPEC_UNLINK_ENTRY_NOT_FOUND", `Spec id '${entryId}' does not exist in the registry index.`)
            ]
        };
    }
    const targetEntry = input.currentDocument.entries[targetIndex];
    const previousLinkedSlice = targetEntry.optional.linked_slice;
    if (previousLinkedSlice === undefined) {
        return {
            ok: false,
            findings: [
                createFinding("SPEC_UNLINK_NOT_LINKED", `Spec id '${entryId}' does not have linked_slice metadata to remove.`)
            ]
        };
    }
    const { linked_slice: _removedLinkedSlice, ...preservedOptional } = targetEntry.optional;
    const updatedAt = (0, traceability_1.parseRegistryTimestampField)(input.unlinkedAt ?? new Date().toISOString(), "updated_at");
    const nextEntry = {
        ...targetEntry,
        source: {
            ...targetEntry.source,
            additionalMetadata: { ...targetEntry.source.additionalMetadata }
        },
        optional: {
            ...preservedOptional,
            updated_at: updatedAt
        },
        additionalMetadata: { ...targetEntry.additionalMetadata }
    };
    return {
        ok: true,
        entry: nextEntry,
        previousLinkedSlice,
        document: (0, document_io_1.applyNonDestructiveSpecIndexEntryUpdate)({
            currentDocument: input.currentDocument,
            targetIndex,
            nextEntry
        })
    };
}
function readEntryId(entryId) {
    if (typeof entryId !== "string" || entryId.trim() === "") {
        throw new TypeError("Spec unlink entry id must be a non-empty string.");
    }
    return entryId.trim();
}
function createFinding(code, message) {
    return {
        code,
        message,
        severity: "error",
        path: cli_constants_1.CLI_SPEC_INDEX_PATH
    };
}
