import { insertAuditLog } from '../modules/common/providers/audit-logs.provider.js';
export async function cleanupExpiredInvitations(db, auth0, logger) {
    const client = await db.pool.connect();
    let deleted = 0;
    let errors = 0;
    try {
        const { rows: expired } = await client.query(`SELECT id, auth0_user_id, auth0_user_created, user_id, business_id
       FROM accounter_schema.invitations
       WHERE accepted_at IS NULL
         AND expires_at < NOW()`);
        for (const invitation of expired) {
            try {
                if (invitation.auth0_user_created && invitation.auth0_user_id) {
                    await auth0.deleteUser(invitation.auth0_user_id);
                }
                await client.query('BEGIN');
                try {
                    await client.query(`DELETE FROM accounter_schema.business_users
             WHERE user_id = $1 AND auth0_user_id IS NULL`, [invitation.user_id]);
                    await client.query('DELETE FROM accounter_schema.invitations WHERE id = $1', [
                        invitation.id,
                    ]);
                    await insertAuditLog.run({
                        ownerId: invitation.business_id,
                        userId: null,
                        auth0UserId: null,
                        action: 'INVITATION_EXPIRED_CLEANUP',
                        entity: 'Invitation',
                        entityId: invitation.id,
                        details: { auth0_user_id: invitation.auth0_user_id },
                        ipAddress: null,
                    }, client);
                    await client.query('COMMIT');
                    deleted++;
                }
                catch (dbError) {
                    await client.query('ROLLBACK');
                    throw dbError;
                }
            }
            catch (err) {
                logger.error('Failed to cleanup invitation', { invitationId: invitation.id, err });
                errors++;
            }
        }
    }
    finally {
        client.release();
    }
    return { deleted, errors };
}
//# sourceMappingURL=cleanup-expired-invitations.js.map