"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuthApiClient = void 0;
const AppError_js_1 = require("../../shared/errors/AppError.js");
const HttpClient_js_1 = require("./HttpClient.js");
class AuthApiClient {
    registerPath;
    loginPath;
    http;
    constructor(baseUrl, registerPath, loginPath) {
        this.registerPath = registerPath;
        this.loginPath = loginPath;
        this.http = new HttpClient_js_1.HttpClient({ baseUrl });
    }
    async registerAdmin(credentials) {
        if (!this.registerPath) {
            return;
        }
        await this.http.post(this.registerPath, credentials);
    }
    async loginAdmin(credentials) {
        if (!this.loginPath) {
            throw new AppError_js_1.ConfigurationError("Admin login is required, but server/README.md does not document an admin login route.");
        }
        const response = await this.http.post(this.loginPath, {
            username: credentials.username ?? credentials.email,
            password: credentials.password
        });
        const payload = response.data ?? response;
        const token = payload.token ?? payload.accessToken ?? payload.jwt;
        if (!token) {
            throw new AppError_js_1.ConfigurationError("Admin login response did not include a JWT token.");
        }
        const expiresAt = payload.expiresAt ?? this.fromExpiresIn(payload.expiresIn);
        return { token, expiresAt };
    }
    fromExpiresIn(expiresIn) {
        if (!expiresIn)
            return undefined;
        return new Date(Date.now() + expiresIn * 1000).toISOString();
    }
}
exports.AuthApiClient = AuthApiClient;
