import { HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { FindActionResDto } from '@api/models';
import { RolesApiClient } from '@api/services';
import { catchError, throwError } from 'rxjs';

export type PASSWORD_MATCH_TYPE = 'MIN_8' | 'a-z' | 'A-Z';

@Injectable({
  providedIn: 'root',
})
export class RuoliService {
  constructor(private rolesApiClient: RolesApiClient) {}

  getRoles() {
    const params = {
      body: {},
    };
    return this.rolesApiClient.rolesControllerFetchRoles(params).pipe(
      catchError((err: HttpErrorResponse) => {
        return throwError(() => err);
      }),
    );
  }

  getAvailablePrivileges(id: number) {
    const params = {
      id: id,
    };
    return this.rolesApiClient
      .rolesControllerGetAvailableRolePrivileges(params)
      .pipe(
        catchError((err: HttpErrorResponse) => {
          return throwError(() => err);
        }),
      );
  }

  setPrivilegesForRole(roleId: number, privilegesIds: FindActionResDto[]) {
    const params = {
      id: roleId,
      body: {
        actionIds: privilegesIds.map((x) => x.id),
      },
    };
    return this.rolesApiClient.rolesControllerSetRolePrivileges(params).pipe(
      catchError((err: HttpErrorResponse) => {
        return throwError(() => err);
      }),
    );
  }

  getPrivilegesById(idRuolo: number) {
    const params = {
      id: idRuolo,
    };
    return this.rolesApiClient.rolesControllerGetRolePrivileges(params).pipe(
      catchError((err: HttpErrorResponse) => {
        return throwError(() => err);
      }),
    );
  }

  changePrivilegeFlagEnabled(privilegeId: number, value: boolean) {
    const params = {
      id: privilegeId,
      body: {
        flagEnabled: value,
      },
    };
    return this.rolesApiClient
      .rolesControllerSetPrivilegeFlagEnabled(params)
      .pipe(
        catchError((err: HttpErrorResponse) => {
          return throwError(() => err);
        }),
      );
  }

  changePrivilegeReadOnlyFlag(privilegeId: number, value: boolean) {
    const params = {
      id: privilegeId,
      body: {
        flagReadOnly: value,
      },
    };
    return this.rolesApiClient
      .rolesControllerSetPrivilegeFlagReadonly(params)
      .pipe(
        catchError((err: HttpErrorResponse) => {
          return throwError(() => err);
        }),
      );
  }

  deletePrivilege(privilegeId: number) {
    const param = {
      id: privilegeId,
    };
    return this.rolesApiClient
      .rolesControllerDeleteRolePrivilege$Response(param)
      .pipe(
        catchError((err: HttpErrorResponse) => {
          return throwError(() => err);
        }),
      );
  }
}
