import crypto from "crypto";
import { Controller, Get, Route, SuccessResponse } from "tsoa";
import { ApiValidationError } from "../../Models/Server.Error.model";

const DELETE_CHALLENGE_TIMEOUT = 15000;
export const challenges = new Map();

export interface INonce {
    nonce: string;
}

@Route("sysadmin-challenges")
export class ChallengesController extends Controller {
    @SuccessResponse(201, "Challenge created successfully")
    @Get("create")
    public async createChallenge(): Promise<INonce | ApiValidationError> {
        try {
            this.setStatus(201);

            const nonce = crypto.randomBytes(32).toString("hex");
            challenges.set(nonce, Date.now());

            setTimeout(() => {
                challenges.delete(nonce);
            }, DELETE_CHALLENGE_TIMEOUT);

            return { nonce };
        } catch (e) {
            const errorOccurred: Error = e as Error;
            this.setStatus(500);
            return new ApiValidationError(500, errorOccurred.message);
        }
    }
}
