import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';

import { environment } from '../../environments/environment';

export type AuditAction = 'CREATE' | 'UPDATE' | 'DELETE';
export type AuditChangeType = 'added' | 'modified' | 'removed';

export interface AuditFieldChangeDto {
  field: string;
  changeType: AuditChangeType;
  oldValue?: string | null;
  newValue?: string | null;
}

export interface AuditLogDto {
  id: string;
  occurredAtUtc: string;
  action: AuditAction | string;
  page: string;
  entityName: string;
  entityId?: string | null;
  entityLabel?: string | null;
  userId?: string | null;
  userName?: string | null;
  userEmail?: string | null;
  requestPath?: string | null;
  requestMethod?: string | null;
  ipAddress?: string | null;
  changes: AuditFieldChangeDto[];
}

export interface PagedResult<T> {
  page: number;
  pageSize: number;
  total: number;
  items: T[];
}

export interface HistoricoQuery {
  pageName?: string;
  action?: AuditAction | string;
  entity?: string;
  user?: string;
  search?: string;
  dateFrom?: string;
  dateTo?: string;
  page?: number;
  pageSize?: number;
}

@Injectable({ providedIn: 'root' })
export class HistoricoService {
  private readonly baseApi: string;

  constructor(private http: HttpClient) {
    const raw = (environment.apiUrl || '').replace(/\/+$/, '');
    this.baseApi = raw.toLowerCase().endsWith('/api') ? raw : `${raw}/api`;
  }

  list(params: HistoricoQuery): Observable<PagedResult<AuditLogDto>> {
    let httpParams = new HttpParams();
    if (params.pageName) httpParams = httpParams.set('pageName', params.pageName);
    if (params.action) httpParams = httpParams.set('action', params.action);
    if (params.entity) httpParams = httpParams.set('entity', params.entity);
    if (params.user) httpParams = httpParams.set('user', params.user);
    if (params.search) httpParams = httpParams.set('search', params.search);
    if (params.dateFrom) httpParams = httpParams.set('dateFrom', params.dateFrom);
    if (params.dateTo) httpParams = httpParams.set('dateTo', params.dateTo);

    httpParams = httpParams.set('page', String(params.page || 1));
    httpParams = httpParams.set('pageSize', String(params.pageSize || 10));

    return this.http.get<PagedResult<AuditLogDto>>(`${this.baseApi}/historico`, { params: httpParams });
  }
}
