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 VigenciaRow {
  id: string;
  item: number;
  conta: string | null;
  linha: string | null;
  cliente: string | null;
  usuario: string | null;
  planoContrato: string | null;
  dtEfetivacaoServico: string | null;
  dtTerminoFidelizacao: string | null;
  autoRenewYears?: number | null;
  autoRenewReferenceEndDate?: string | null;
  autoRenewConfiguredAt?: string | null;
  lastAutoRenewedAt?: string | null;
  total: number | null;
  createdAt?: string | null;
  updatedAt?: string | null;
}

export interface UpdateVigenciaRequest {
  item?: number | null;
  conta?: string | null;
  linha?: string | null;
  cliente?: string | null;
  usuario?: string | null;
  planoContrato?: string | null;
  dtEfetivacaoServico?: string | null;
  dtTerminoFidelizacao?: string | null;
  total?: number | null;
}

export interface CreateVigenciaRequest extends UpdateVigenciaRequest {}
export interface ConfigureVigenciaRenewalRequest {
  years: 2;
}

export interface VigenciaClientGroup {
  cliente: string;
  linhas: number;
  total: number;
  vencidos: number;
  aVencer30: number;
  proximoVencimento: string | null;
  ultimoVencimento: string | null;
}

// ✅ NOVAS INTERFACES DE RESPOSTA
export interface VigenciaKpis {
  totalClientes: number;
  totalLinhas: number;
  totalVencidos: number;
  valorTotal: number;
}

export interface VigenciaGroupResponse {
  data: PagedResult<VigenciaClientGroup>;
  kpis: VigenciaKpis;
}

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

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

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

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

    return this.http.get<PagedResult<VigenciaRow>>(`${this.baseApi}/lines/vigencia`, { params });
  }

  // ✅ Retorna o objeto composto (Dados + KPIs)
  getGroups(opts: { search?: string; page?: number; pageSize?: number; sortBy?: string; sortDir?: SortDir; }): Observable<VigenciaGroupResponse> {
    let params = new HttpParams();
    if (opts.search && opts.search.trim()) params = params.set('search', opts.search.trim());

    params = params.set('page', String(opts.page ?? 1));
    params = params.set('pageSize', String(opts.pageSize ?? 20));
    params = params.set('sortBy', (opts.sortBy ?? 'cliente').trim());
    params = params.set('sortDir', opts.sortDir ?? 'asc');

    return this.http.get<VigenciaGroupResponse>(`${this.baseApi}/lines/vigencia/groups`, { params });
  }

  getClients(): Observable<string[]> {
    return this.http.get<string[]>(`${this.baseApi}/lines/vigencia/clients`);
  }

  getById(id: string): Observable<VigenciaRow> {
    return this.http.get<VigenciaRow>(`${this.baseApi}/lines/vigencia/${id}`);
  }

  update(id: string, payload: UpdateVigenciaRequest): Observable<void> {
    return this.http.put<void>(`${this.baseApi}/lines/vigencia/${id}`, payload);
  }

  create(payload: CreateVigenciaRequest): Observable<VigenciaRow> {
    return this.http.post<VigenciaRow>(`${this.baseApi}/lines/vigencia`, payload);
  }

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

  configureAutoRenew(id: string, payload: ConfigureVigenciaRenewalRequest): Observable<void> {
    return this.http.post<void>(`${this.baseApi}/lines/vigencia/${id}/renew`, payload);
  }
}
