import { Injectable } from '@angular/core';
import { GenericService } from '@iqser/common-ui';
import { forkJoin, Observable, of } from 'rxjs';
import {
    IDigitalSignatureRequest,
    IKmsDigitalSignature,
    IKmsDigitalSignatureRequest,
    IPkcsDigitalSignature,
    IPkcsDigitalSignatureRequest,
} from '@red/domain';
import { catchError, map } from 'rxjs/operators';
import { filterEach } from '@iqser/common-ui/lib/utils';

@Injectable()
export class DigitalSignatureService extends GenericService<IDigitalSignatureRequest> {
    protected readonly _defaultModelPath = 'digital-signature';

    updateSignature(body: IPkcsDigitalSignatureRequest): Observable<unknown> {
        return this._put(body);
    }

    saveSignature(body: IPkcsDigitalSignature): Observable<IPkcsDigitalSignatureRequest> {
        return this._post(body);
    }

    saveKmsSignature(body: IKmsDigitalSignature): Observable<IKmsDigitalSignatureRequest> {
        return this._post(body, `${this._defaultModelPath}/kms`);
    }

    deleteSignature(): Observable<unknown> {
        return super.delete({});
    }

    deleteKmsSignature(): Observable<unknown> {
        return super.delete({}, `${this._defaultModelPath}/kms`);
    }

    getSignature(): Observable<IDigitalSignatureRequest> {
        const digitalSignature$ = super.getAll().pipe(catchError(() => of(null)));
        const kmsDigitalSignature$ = super.getAll(`${this._defaultModelPath}/kms`).pipe(catchError(() => of(null)));
        return forkJoin([digitalSignature$, kmsDigitalSignature$]).pipe(
            filterEach(signature => !!signature),
            map(signatures => signatures[0] as IDigitalSignatureRequest),
        );
    }
}
