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';
export class InvalidGithubTokenError extends Error {
    constructor(message) {
        super(message);
        this.name = 'InvalidGithubTokenError';
    }
}
const VALIDATE_URL = 'https://api.github.com/user';
let ConnectGithubUseCase = class ConnectGithubUseCase {
    repo;
    constructor(repo) {
        this.repo = repo;
    }
    async execute(input) {
        const token = input.token?.trim();
        if (!token)
            throw new InvalidGithubTokenError('Token is required');
        // Probe the token before persisting — never store an invalid token.
        const res = await fetch(VALIDATE_URL, {
            headers: {
                Authorization: `Bearer ${token}`,
                'User-Agent': 'shep-github-integration',
                Accept: 'application/vnd.github+json',
            },
        });
        if (res.status === 401) {
            throw new InvalidGithubTokenError('GitHub rejected the token (401). Check that the PAT is correct and has not expired.');
        }
        if (!res.ok) {
            throw new InvalidGithubTokenError(`Could not validate token: GitHub returned ${res.status} ${res.statusText}`);
        }
        const body = (await res.json().catch(() => ({})));
        if (!body.login) {
            throw new InvalidGithubTokenError('GitHub did not return a user — token may lack `read:user` scope');
        }
        await this.repo.set(token);
        return { login: body.login };
    }
};
ConnectGithubUseCase = __decorate([
    injectable(),
    __param(0, inject('IGithubIntegrationRepository')),
    __metadata("design:paramtypes", [Object])
], ConnectGithubUseCase);
export { ConnectGithubUseCase };
