import {Injectable} from "@angular/core";
import {HttpClient} from "@angular/common/http";
import {Router} from "@angular/router";
import {AuthenticationService} from "../../modules/security/authentication.service";

@Injectable({
              providedIn: "root"
            })
export class AuditService {
  constructor(private httpClient: HttpClient,
              private router: Router,
              private authService: AuthenticationService) {
  }

  public logActionAudit(eventType: string, filterInfo?: Record<string, FilterInfo>,
                        fileName?: string): void {
    if (this.authService.isAuthenticated()) {
      const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
      const route = this.router.url;
      const sourceUrl = window.location.href;
      const auditEvent: AuditAction = {
        eventType: eventType,
        route: route,
        sourceUrl: sourceUrl,
        filterInfo: filterInfo,
        fileName: fileName
      }
      this.httpClient.post("audit/action", auditEvent, {
        headers: {
          "Client-Time-Zone": timeZone,
        }
      }).toPromise();
    }
  }
}


export class AuditConstants {
  public static readonly OPEN_PAGE_EVENT = "Открытие страницы";
  public static readonly FILTER_EVENT = "Поиск по фильтру";
}

export interface AuditAction {
  eventType: string;
  route: string;
  sourceUrl: string;
  filterInfo?: Record<string, FilterInfo>;
  fileName?: string
}

export interface FilterInfo {
  conditionOperator?: string;
  conditions: FilterCondition[];
}

export interface FilterCondition {
  filterValue: string;
  filterType: string;
}