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

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

export interface ParcelamentoListItem {
  id: string;
  anoRef?: number | null;
  item?: number | null;
  linha?: string | null;
  cliente?: string | null;
  qtParcelas?: string | null;
  parcelaAtual?: number | null;
  totalParcelas?: number | null;
  valorCheio?: number | string | null;
  desconto?: number | string | null;
  valorComDesconto?: number | string | null;
}

export interface ParcelamentoParcela {
  competencia: string;
  valor?: number | string | null;
}

export interface ParcelamentoAnnualMonth {
  month: number;
  valor?: number | string | null;
}

export interface ParcelamentoAnnualRow {
  year: number;
  total?: number | string | null;
  months?: ParcelamentoAnnualMonth[];
}

export interface ParcelamentoMonthInput {
  competencia: string;
  valor?: number | string | null;
}

export interface ParcelamentoUpsertRequest {
  anoRef?: number | null;
  item?: number | null;
  linha?: string | null;
  cliente?: string | null;
  qtParcelas?: string | null;
  parcelaAtual?: number | null;
  totalParcelas?: number | null;
  valorCheio?: number | string | null;
  desconto?: number | string | null;
  valorComDesconto?: number | string | null;
  monthValues?: ParcelamentoMonthInput[] | null;
}

export interface ParcelamentoDetail extends ParcelamentoListItem {
  parcelasMensais?: ParcelamentoParcela[];
  annualRows?: ParcelamentoAnnualRow[];
}

export interface ParcelamentoDetailResponse extends ParcelamentoListItem {
  parcelasMensais?: ParcelamentoParcela[];
  parcelas?: ParcelamentoParcela[];
  monthValues?: ParcelamentoParcela[];
  annualRows?: ParcelamentoAnnualRow[];
}

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

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

  list(filters: {
    anoRef?: number;
    linha?: string;
    cliente?: string;
    competenciaAno?: number;
    competenciaMes?: number;
    page?: number;
    pageSize?: number;
  }): Observable<PagedResult<ParcelamentoListItem>> {
    let params = new HttpParams();
    if (filters.anoRef !== undefined) params = params.set('anoRef', String(filters.anoRef));
    if (filters.linha && filters.linha.trim()) params = params.set('linha', filters.linha.trim());
    if (filters.cliente && filters.cliente.trim()) params = params.set('cliente', filters.cliente.trim());
    if (filters.competenciaAno !== undefined) params = params.set('competenciaAno', String(filters.competenciaAno));
    if (filters.competenciaMes !== undefined) params = params.set('competenciaMes', String(filters.competenciaMes));
    params = params.set('page', String(filters.page ?? 1));
    params = params.set('pageSize', String(filters.pageSize ?? 10));

    return this.http.get<PagedResult<ParcelamentoListItem>>(`${this.baseApi}/parcelamentos`, { params });
  }

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

  create(payload: ParcelamentoUpsertRequest): Observable<ParcelamentoDetailResponse> {
    return this.http.post<ParcelamentoDetailResponse>(`${this.baseApi}/parcelamentos`, payload);
  }

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

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