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 { ApplicationNotFoundError } from '../../../domain/errors/application-not-found.error.js';
import { cleanDeployName } from '../../../domain/shared/clean-name.js';
import { OperationLogKind } from '../../../domain/generated/output.js';
let CreateGitRemoteUseCase = class CreateGitRemoteUseCase {
    applicationRepo;
    gitRemoteService;
    opLog;
    constructor(applicationRepo, gitRemoteService, opLog) {
        this.applicationRepo = applicationRepo;
        this.gitRemoteService = gitRemoteService;
        this.opLog = opLog;
    }
    async execute(input) {
        // Backward compat: callers that pass a bare string still work.
        const normalized = typeof input === 'string' ? { applicationId: input } : input;
        const opKind = OperationLogKind.GitRemoteCreate;
        const opId = normalized.applicationId;
        await this.opLog.info(opKind, opId, 'Starting GitHub repository creation');
        const app = await this.applicationRepo.findById(normalized.applicationId);
        if (!app) {
            await this.opLog.error(opKind, opId, `Application not found: ${normalized.applicationId}`);
            throw new ApplicationNotFoundError(normalized.applicationId);
        }
        const trimmedRepoName = normalized.repoName?.trim();
        const trimmedOwnerLogin = normalized.ownerLogin?.trim();
        try {
            const { remoteUrl } = await this.gitRemoteService.createGitHubRepoAndPush({
                cwd: app.repositoryPath,
                // Prefer the user-supplied name; fall back to the clean
                // display-name-derived slug so CLI / API callers that omit
                // `repoName` still get a human-readable GitHub repo name
                // instead of the internal slug with its random hex suffix.
                slug: trimmedRepoName && trimmedRepoName.length > 0
                    ? trimmedRepoName
                    : cleanDeployName(app.name),
                description: app.description,
                visibility: normalized.visibility ?? 'private',
                ownerLogin: trimmedOwnerLogin && trimmedOwnerLogin.length > 0 ? trimmedOwnerLogin : undefined,
                onLog: (level, message, detail) => {
                    // Translate the port's string union into an opLog method. Fire-and-
                    // forget — log persistence must never gate the actual operation.
                    const persisted = (() => {
                        switch (level) {
                            case 'debug':
                                return this.opLog.debug(opKind, opId, message, detail);
                            case 'warn':
                                return this.opLog.warn(opKind, opId, message, detail);
                            case 'error':
                                return this.opLog.error(opKind, opId, message, detail);
                            case 'info':
                            default:
                                return this.opLog.info(opKind, opId, message, detail);
                        }
                    })();
                    void persisted;
                },
            });
            await this.applicationRepo.update(normalized.applicationId, { gitRemoteUrl: remoteUrl });
            await this.opLog.info(opKind, opId, `Persisted gitRemoteUrl on application: ${remoteUrl}`);
            return { remoteUrl };
        }
        catch (err) {
            const message = err instanceof Error ? err.message : String(err);
            await this.opLog.error(opKind, opId, `GitHub repo creation failed: ${message}`, err instanceof Error && err.stack ? err.stack : undefined);
            // Re-throw — the route layer turns the structured error into the right
            // HTTP status code.
            throw err;
        }
    }
};
CreateGitRemoteUseCase = __decorate([
    injectable(),
    __param(0, inject('IApplicationRepository')),
    __param(1, inject('IGitRemoteService')),
    __param(2, inject('IOperationLogService')),
    __metadata("design:paramtypes", [Object, Object, Object])
], CreateGitRemoteUseCase);
export { CreateGitRemoteUseCase };
