"use strict";
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); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ApiTokenRepository = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("@nestjs/typeorm");
const typeorm_2 = require("typeorm");
const api_token_entity_1 = require("../entities/api-token.entity");
const credentials_entity_1 = require("../../management/entities/credentials.entity");
const credential_purpose_enum_1 = require("../enums/credential-purpose.enum");
let ApiTokenRepository = class ApiTokenRepository {
    constructor(apiTokenRepo) {
        this.apiTokenRepo = apiTokenRepo;
    }
    async createToken(provider, label, notes, encryptedToken, options) {
        const token = this.apiTokenRepo.create({
            provider,
            label,
            notes,
            encrypted_token: encryptedToken,
            credential_type: options?.credentialType ?? credentials_entity_1.CredentialType.API_KEY,
            encrypted_access_key: options?.encryptedAccessKey ?? null,
            expires_at: options?.expiresAt ?? null,
            purpose: options?.purpose ?? credential_purpose_enum_1.CredentialPurpose.COMPUTE,
        });
        return this.apiTokenRepo.save(token);
    }
    async findAll() {
        return this.apiTokenRepo.find({
            where: { is_active: true },
        });
    }
    async findById(id) {
        return this.apiTokenRepo.findOneBy({ id, is_active: true });
    }
    async updateLastUsed(id) {
        const token = await this.findById(id);
        if (!token) {
            throw new Error(`API token with ID ${id} not found`);
        }
        token.last_used_at = new Date();
        await this.apiTokenRepo.save(token);
    }
    async getEncryptedToken(id) {
        const token = await this.findById(id);
        if (!token) {
            throw new Error(`API token with ID ${id} not found`);
        }
        token.last_used_at = new Date();
        await this.apiTokenRepo.save(token);
        return token.encrypted_token;
    }
    async getEncryptedAccessKey(id) {
        const token = await this.findById(id);
        if (!token) {
            throw new Error(`API token with ID ${id} not found`);
        }
        return token.encrypted_access_key ?? null;
    }
    async updateExpiry(id, expiresAt) {
        const result = await this.apiTokenRepo.update({ id, is_active: true }, { expires_at: expiresAt });
        if (result.affected === 0) {
            throw new Error(`API token with ID ${id} not found`);
        }
    }
    async deleteToken(id) {
        const result = await this.apiTokenRepo.delete({ id, is_active: true });
        if (result.affected === 0) {
            throw new Error(`API token with ID ${id} not found`);
        }
    }
    async findByProvider(provider) {
        return this.apiTokenRepo.find({
            where: { provider, is_active: true },
        });
    }
    async findByProviderAndPurpose(provider, purpose) {
        return this.apiTokenRepo.find({
            where: { provider, is_active: true, purpose },
        });
    }
};
exports.ApiTokenRepository = ApiTokenRepository;
exports.ApiTokenRepository = ApiTokenRepository = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_1.InjectRepository)(api_token_entity_1.ApiTokenEntity)),
    __metadata("design:paramtypes", [typeorm_2.Repository])
], ApiTokenRepository);
