"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.rotateRefreshSession = exports.revokeAllActorSessions = exports.revokeRefreshSession = exports.findValidRefreshSession = exports.createAuthSession = void 0;
const drizzle_orm_1 = require("drizzle-orm");
const index_js_1 = require("../db/index.js");
const schema_js_1 = require("../db/schema.js");
const authSecurity_js_1 = require("./authSecurity.js");
const createAuthSession = async ({ actorType, actorId, role, userAgent, ipAddress, }) => {
    const refreshToken = (0, authSecurity_js_1.generateRefreshToken)();
    const refreshTokenHash = (0, authSecurity_js_1.hashRefreshToken)(refreshToken);
    await index_js_1.db.insert(schema_js_1.authSessions).values({
        actorType,
        actorId,
        refreshTokenHash,
        userAgent,
        ipAddress,
        expiresAt: (0, authSecurity_js_1.refreshTokenExpiryDate)(),
        lastUsedAt: new Date(),
    });
    const accessToken = (0, authSecurity_js_1.signAccessToken)({
        sub: actorId.toString(),
        actorType,
        role,
    });
    return { accessToken, refreshToken };
};
exports.createAuthSession = createAuthSession;
const findValidRefreshSession = async (refreshToken) => {
    const refreshTokenHash = (0, authSecurity_js_1.hashRefreshToken)(refreshToken);
    const [session] = await index_js_1.db
        .select()
        .from(schema_js_1.authSessions)
        .where((0, drizzle_orm_1.and)((0, drizzle_orm_1.eq)(schema_js_1.authSessions.refreshTokenHash, refreshTokenHash), (0, drizzle_orm_1.isNull)(schema_js_1.authSessions.revokedAt), (0, drizzle_orm_1.gt)(schema_js_1.authSessions.expiresAt, new Date())))
        .limit(1);
    return session ?? null;
};
exports.findValidRefreshSession = findValidRefreshSession;
const revokeRefreshSession = async (refreshToken) => {
    await index_js_1.db
        .update(schema_js_1.authSessions)
        .set({ revokedAt: new Date() })
        .where((0, drizzle_orm_1.eq)(schema_js_1.authSessions.refreshTokenHash, (0, authSecurity_js_1.hashRefreshToken)(refreshToken)));
};
exports.revokeRefreshSession = revokeRefreshSession;
const revokeAllActorSessions = async (actorType, actorId) => {
    await index_js_1.db
        .update(schema_js_1.authSessions)
        .set({ revokedAt: new Date() })
        .where((0, drizzle_orm_1.and)((0, drizzle_orm_1.eq)(schema_js_1.authSessions.actorType, actorType), (0, drizzle_orm_1.eq)(schema_js_1.authSessions.actorId, actorId), (0, drizzle_orm_1.isNull)(schema_js_1.authSessions.revokedAt)));
};
exports.revokeAllActorSessions = revokeAllActorSessions;
const rotateRefreshSession = async ({ oldRefreshToken, actorType, actorId, role, userAgent, ipAddress, }) => {
    await (0, exports.revokeRefreshSession)(oldRefreshToken);
    return (0, exports.createAuthSession)({ actorType, actorId, role, userAgent, ipAddress });
};
exports.rotateRefreshSession = rotateRefreshSession;
//# sourceMappingURL=sessionService.js.map