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

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

export interface MobileLineList {
  id: string;
  item: number;
  conta: string | null;
  linha: string | null;
  chip: string | null;
  cliente: string | null;
  usuario: string | null;
  planoContrato: string | null;
  status: string | null;
  skil: string | null;
  modalidade: string | null;
  vencConta: string | null;
}

export interface MobileLineDetail extends MobileLineList {
  franquiaVivo?: number | null;
  valorPlanoVivo?: number | null;
  gestaoVozDados?: number | null;
  skeelo?: number | null;
  vivoNewsPlus?: number | null;
  vivoTravelMundo?: number | null;
  vivoGestaoDispositivo?: number | null;
  valorContratoVivo?: number | null;

  franquiaLine?: number | null;
  franquiaGestao?: number | null;
  locacaoAp?: number | null;
  valorContratoLine?: number | null;

  desconto?: number | null;
  lucro?: number | null;

  dataBloqueio?: string | null;
  cedente?: string | null;
  solicitante?: string | null;
  dataEntregaOpera?: string | null;
  dataEntregaCliente?: string | null;
  dtEfetivacaoServico?: string | null;
  dtTerminoFidelizacao?: string | null;
}

export interface LineOption {
  id: string;
  linha: string;
}

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

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

  getLines(page: number, pageSize: number, search: string): Observable<PagedResult<MobileLineList>> {
    let params = new HttpParams()
      .set('page', String(page))
      .set('pageSize', String(pageSize));

    const s = (search ?? '').trim();
    if (s) params = params.set('search', s);

    return this.http.get<PagedResult<MobileLineList>>(this.baseUrl, { params });
  }

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

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

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

  importExcel(file: File): Observable<{ imported: number }> {
    const form = new FormData();
    form.append('file', file);
    return this.http.post<{ imported: number }>(`${this.baseUrl}/import-excel`, form);
  }

  getClients(skil?: string): Observable<string[]> {
    let params = new HttpParams();
    const s = (skil ?? '').trim();
    if (s) params = params.set('skil', s);
    return this.http.get<string[]>(`${this.baseUrl}/clients`, { params });
  }

  getGroups(page: number, pageSize: number, skil?: string, search?: string) {
    let params = new HttpParams()
      .set('page', String(page))
      .set('pageSize', String(pageSize));

    const sk = (skil ?? '').trim();
    if (sk) params = params.set('skil', sk);

    const se = (search ?? '').trim();
    if (se) params = params.set('search', se);

    return this.http.get<PagedResult<any>>(`${this.baseUrl}/groups`, { params });
  }

  // ✅ NOVO: usado no modal do MUREG
  // Precisa existir no backend: GET /api/lines/by-client?cliente=...
  getLinesByClient(cliente: string): Observable<LineOption[]> {
    let params = new HttpParams().set('cliente', (cliente ?? '').trim());
    return this.http.get<LineOption[]>(`${this.baseUrl}/by-client`, { params });
  }
}
