/**
 * ConfigureSupervisorUseCase
 *
 * Creates or replaces a {@link SupervisorPolicy} for the
 * (scopeType, scopeId?, featureId?) scope. Validation is performed
 * before any persistence so callers see typed
 * {@link InvalidSupervisorPolicyError} rejections rather than partial
 * writes.
 *
 * Behaviour:
 *  - When no policy exists for the scope, a new row is inserted with
 *    `enabled = true` (callers explicitly disable via
 *    DisableSupervisorUseCase).
 *  - When a policy already exists for the scope, all configurable
 *    fields are replaced and `updatedAt` is bumped — `id` and
 *    `createdAt` are preserved.
 */
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); }
};
import { inject, injectable } from 'tsyringe';
import { randomUUID } from 'node:crypto';
import { SupervisorAutonomy, } from '../../../domain/generated/output.js';
import { InvalidSupervisorPolicyError } from '../../../domain/errors/invalid-supervisor-policy.error.js';
/** Approval-gate keys recognised by gateAuthority overrides. */
const VALID_GATE_KEYS = ['prd', 'plan', 'merge'];
const VALID_AUTONOMY_VALUES = new Set(Object.values(SupervisorAutonomy));
let ConfigureSupervisorUseCase = class ConfigureSupervisorUseCase {
    policyRepository;
    constructor(policyRepository) {
        this.policyRepository = policyRepository;
    }
    async execute(input) {
        validateInput(input);
        // Look up by exact scope so a feature-scoped configure does not pick up
        // a scope-level fallback row.
        const existing = input.featureId !== undefined
            ? await this.policyRepository.findByScopeAndFeature(input.scopeType, input.scopeId, input.featureId)
            : await this.policyRepository.findByScope(input.scopeType, input.scopeId);
        const now = new Date();
        const policy = {
            id: existing?.id ?? randomUUID(),
            scopeType: input.scopeType,
            scopeId: input.scopeId,
            featureId: input.featureId,
            enabled: existing?.enabled ?? true,
            autonomyLevel: input.autonomyLevel,
            modelId: input.modelId,
            promptVersion: input.promptVersion,
            gateAuthorityJson: input.gateAuthority && Object.keys(input.gateAuthority).length > 0
                ? JSON.stringify(input.gateAuthority)
                : undefined,
            policyRulesJson: input.policyRules && input.policyRules.length > 0
                ? JSON.stringify(input.policyRules)
                : undefined,
            notificationOverridesJson: input.notificationOverrides && Object.keys(input.notificationOverrides).length > 0
                ? JSON.stringify(input.notificationOverrides)
                : undefined,
            createdAt: existing?.createdAt ?? now,
            updatedAt: now,
        };
        if (existing) {
            await this.policyRepository.update(policy);
        }
        else {
            await this.policyRepository.create(policy);
        }
        return policy;
    }
};
ConfigureSupervisorUseCase = __decorate([
    injectable(),
    __param(0, inject('ISupervisorPolicyRepository')),
    __metadata("design:paramtypes", [Object])
], ConfigureSupervisorUseCase);
export { ConfigureSupervisorUseCase };
function validateInput(input) {
    if (typeof input.scopeType !== 'string' || input.scopeType.trim().length === 0) {
        throw new InvalidSupervisorPolicyError('scopeType', 'must be a non-empty string');
    }
    if (input.featureId?.trim().length === 0) {
        throw new InvalidSupervisorPolicyError('featureId', 'must be a non-empty string when supplied');
    }
    if (!VALID_AUTONOMY_VALUES.has(input.autonomyLevel)) {
        throw new InvalidSupervisorPolicyError('autonomyLevel', `must be one of ${[...VALID_AUTONOMY_VALUES].join(', ')}`);
    }
    if (input.gateAuthority) {
        for (const [gate, autonomy] of Object.entries(input.gateAuthority)) {
            if (!VALID_GATE_KEYS.includes(gate)) {
                throw new InvalidSupervisorPolicyError(`gateAuthority.${gate}`, `unknown gate key (expected one of ${VALID_GATE_KEYS.join(', ')})`);
            }
            if (autonomy === undefined || !VALID_AUTONOMY_VALUES.has(autonomy)) {
                throw new InvalidSupervisorPolicyError(`gateAuthority.${gate}`, `must be a valid SupervisorAutonomy`);
            }
        }
    }
    if (input.policyRules) {
        input.policyRules.forEach((rule, idx) => {
            if (!rule || typeof rule !== 'object') {
                throw new InvalidSupervisorPolicyError(`policyRules[${idx}]`, 'must be an object');
            }
            if (typeof rule.ruleId !== 'string' || rule.ruleId.trim().length === 0) {
                throw new InvalidSupervisorPolicyError(`policyRules[${idx}].ruleId`, 'must be a non-empty string');
            }
            if (typeof rule.condition !== 'string') {
                throw new InvalidSupervisorPolicyError(`policyRules[${idx}].condition`, 'must be a string');
            }
            if (typeof rule.action !== 'string') {
                throw new InvalidSupervisorPolicyError(`policyRules[${idx}].action`, 'must be a string');
            }
        });
    }
}
