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

export type SortDir = 'asc' | 'desc';

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

export interface UserDataRow {
  id: string;
  item: number;
  linha: string | null;
  cliente: string | null;
  tipoPessoa?: string | null;
  nome?: string | null;
  razaoSocial?: string | null;
  cnpj?: string | null;
  cpf: string | null;
  email: string | null;
  celular: string | null;
  rg: string | null;
  endereco: string | null;
  telefoneFixo: string | null;
  dataNascimento: string | null;
}

export interface UpdateUserDataRequest {
  item?: number | null;
  linha?: string | null;
  cliente?: string | null;
  tipoPessoa?: string | null;
  nome?: string | null;
  razaoSocial?: string | null;
  cnpj?: string | null;
  cpf?: string | null;
  rg?: string | null;
  dataNascimento?: string | null;
  email?: string | null;
  endereco?: string | null;
  celular?: string | null;
  telefoneFixo?: string | null;
}

export interface CreateUserDataRequest extends UpdateUserDataRequest {}

export interface UserDataClientGroup {
  cliente: string;
  totalRegistros: number;
  comCpf: number;
  comCnpj: number;
  comEmail: number;
}

export interface UserDataKpis {
  totalRegistros: number;
  clientesUnicos: number;
  comCpf: number;
  comCnpj: number;
  comEmail: number;
}

export interface UserDataGroupResponse {
  data: PagedResult<UserDataClientGroup>;
  kpis: UserDataKpis;
}

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

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

  getGroups(opts: { 
    search?: string; 
    tipo?: string;
    page?: number; 
    pageSize?: number; 
    sortBy?: string; 
    sortDir?: SortDir; 
  }): Observable<UserDataGroupResponse> {
    let params = new HttpParams();
    if (opts.search) params = params.set('search', opts.search);
    if (opts.tipo) params = params.set('tipo', opts.tipo);

    params = params.set('page', String(opts.page || 1));
    params = params.set('pageSize', String(opts.pageSize || 10));
    params = params.set('sortBy', opts.sortBy || 'cliente');
    params = params.set('sortDir', opts.sortDir || 'asc');

    return this.http.get<UserDataGroupResponse>(`${this.baseApi}/user-data/groups`, { params });
  }

  getRows(opts: { 
    search?: string; 
    client?: string; 
    tipo?: string;
    page?: number; 
    pageSize?: number; 
    sortBy?: string; 
    sortDir?: SortDir; 
  }): Observable<PagedResult<UserDataRow>> {
    let params = new HttpParams();
    if (opts.search) params = params.set('search', opts.search);
    if (opts.client) params = params.set('client', opts.client);
    if (opts.tipo) params = params.set('tipo', opts.tipo);

    params = params.set('page', String(opts.page || 1));
    params = params.set('pageSize', String(opts.pageSize || 20));
    params = params.set('sortBy', opts.sortBy || 'item');
    params = params.set('sortDir', opts.sortDir || 'asc');

    return this.http.get<PagedResult<UserDataRow>>(`${this.baseApi}/user-data`, { params });
  }

  getClients(tipo?: string): Observable<string[]> {
    let params = new HttpParams();
    if (tipo) params = params.set('tipo', tipo);
    return this.http.get<string[]>(`${this.baseApi}/user-data/clients`, { params });
  }
  
  getById(id: string): Observable<UserDataRow> {
      return this.http.get<UserDataRow>(`${this.baseApi}/user-data/${id}`);
  }

  update(id: string, payload: UpdateUserDataRequest): Observable<void> {
    return this.http.put<void>(`${this.baseApi}/user-data/${id}`, payload);
  }

  create(payload: CreateUserDataRequest): Observable<UserDataRow> {
    return this.http.post<UserDataRow>(`${this.baseApi}/user-data`, payload);
  }

  remove(id: string): Observable<void> {
    return this.http.delete<void>(`${this.baseApi}/user-data/${id}`);
  }
}
