import { AbstractRepository, InvalidValueError } from '@crosslab/service-common';
import { peerconnectionUrlFromId } from '../../methods/urlFromId.js';
import { PeerconnectionModel } from '../model.js';
export class PeerconnectionRepository extends AbstractRepository {
    dependencies = {};
    constructor() {
        super('Peerconnection');
    }
    dependenciesMet() {
        return true;
    }
    initialize(entityManager) {
        this.repository = entityManager.getRepository(PeerconnectionModel);
    }
    async create(data) {
        const model = await super.create(data);
        model.status = 'new';
        return model;
    }
    async write(model, data) {
        if (data.type)
            model.type = data.type;
        if (data.devices && data.devices.length !== 2) {
            throw new InvalidValueError(`Peerconnections need exactly 2 devices, received ${data.devices?.length}`, 400);
        }
        if (data.devices) {
            const deviceA = data.devices[0];
            const deviceB = data.devices[1];
            if (!deviceA.url || !deviceB.url) {
                throw new InvalidValueError('One of the provided devices does not have a url', 400);
            }
            model.deviceA = { ...deviceA, status: 'new' };
            model.deviceB = { ...deviceB, status: 'new' };
        }
        model.configuration = data.configuration ?? {};
    }
    async format(model) {
        return {
            url: peerconnectionUrlFromId(model.uuid),
            type: model.type,
            status: model.status,
            devices: [{ ...model.deviceA }, { ...model.deviceB }],
        };
    }
    formatOverview(model) {
        return {
            url: peerconnectionUrlFromId(model.uuid),
            type: model.type,
            status: model.status,
            devices: [{ url: model.deviceA.url }, { url: model.deviceB.url }],
        };
    }
}
//# sourceMappingURL=peerconnection.js.map