import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { ApiConfigService } from '../../../core/services/api-config.service';
import {
  PagedResult, SystemLogListItem, SystemLogDetail, SystemLogQuery,
  AuditLogListItem, AuditLogDetail, AuditLogQuery, AuditCatalog,
} from '../models/logging.model';

@Injectable({ providedIn: 'root' })
export class LoggingApiService {
  private readonly systemEndpoint: string;
  private readonly auditEndpoint: string;

  constructor(private http: HttpClient, apiConfig: ApiConfigService) {
    this.systemEndpoint = apiConfig.getApiUrl('system-logs');
    this.auditEndpoint  = apiConfig.getApiUrl('audit-logs');
  }

  private toParams(q: Record<string, unknown>): HttpParams {
    let p = new HttpParams();
    for (const [key, value] of Object.entries(q)) {
      if (value !== undefined && value !== null && value !== '') {
        p = p.set(key, String(value));
      }
    }
    return p;
  }

  // ── System logs ─────────────────────────────────────────────────────────────
  getSystemLogs(query: SystemLogQuery): Observable<PagedResult<SystemLogListItem>> {
    return this.http.get<PagedResult<SystemLogListItem>>(
      this.systemEndpoint, { params: this.toParams(query as Record<string, unknown>) });
  }

  getSystemLog(id: number): Observable<SystemLogDetail> {
    return this.http.get<SystemLogDetail>(`${this.systemEndpoint}/${id}`);
  }

  // ── Audit logs ──────────────────────────────────────────────────────────────
  getAuditLogs(query: AuditLogQuery): Observable<PagedResult<AuditLogListItem>> {
    return this.http.get<PagedResult<AuditLogListItem>>(
      this.auditEndpoint, { params: this.toParams(query as Record<string, unknown>) });
  }

  getAuditLog(id: number): Observable<AuditLogDetail> {
    return this.http.get<AuditLogDetail>(`${this.auditEndpoint}/${id}`);
  }

  getAuditCatalog(): Observable<AuditCatalog> {
    return this.http.get<AuditCatalog>(`${this.auditEndpoint}/catalog`);
  }
}
