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 ChipVirgemListDto {
  id: string;
  item: number;
  numeroDoChip: string | null;
  observacoes: string | null;
  createdAt?: string | null;
  updatedAt?: string | null;
}

export interface UpdateChipVirgemRequest {
  item?: number | null;
  numeroDoChip?: string | null;
  observacoes?: string | null;
}

export interface CreateChipVirgemRequest extends UpdateChipVirgemRequest {}

export interface ControleRecebidoListDto {
  id: string;
  ano: number | null;
  item: number | null;
  notaFiscal: string | null;
  chip: string | null;
  serial: string | null;
  conteudoDaNf: string | null;
  numeroDaLinha: string | null;
  valorUnit: number | null;
  valorDaNf: number | null;
  dataDaNf: string | null;
  dataDoRecebimento: string | null;
  quantidade: number | null;
  isResumo: boolean | null;
  createdAt?: string | null;
  updatedAt?: string | null;
}

export interface UpdateControleRecebidoRequest {
  ano?: number | null;
  item?: number | null;
  notaFiscal?: string | null;
  chip?: string | null;
  serial?: string | null;
  conteudoDaNf?: string | null;
  numeroDaLinha?: string | null;
  valorUnit?: number | null;
  valorDaNf?: number | null;
  dataDaNf?: string | null;
  dataDoRecebimento?: string | null;
  quantidade?: number | null;
  isResumo?: boolean | null;
}

export interface CreateControleRecebidoRequest extends UpdateControleRecebidoRequest {}

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

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

  getChipsVirgens(opts: {
    search?: string;
    page?: number;
    pageSize?: number;
    sortBy?: string;
    sortDir?: SortDir;
  }): Observable<PagedResult<ChipVirgemListDto>> {
    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 ?? 'item').trim());
    params = params.set('sortDir', opts.sortDir ?? 'asc');

    return this.http.get<PagedResult<ChipVirgemListDto>>(`${this.baseApi}/chips-virgens`, { params });
  }

  getChipVirgemById(id: string): Observable<ChipVirgemListDto> {
    return this.http.get<ChipVirgemListDto>(`${this.baseApi}/chips-virgens/${id}`);
  }

  updateChipVirgem(id: string, payload: UpdateChipVirgemRequest): Observable<void> {
    return this.http.put<void>(`${this.baseApi}/chips-virgens/${id}`, payload);
  }

  createChipVirgem(payload: CreateChipVirgemRequest): Observable<ChipVirgemListDto> {
    return this.http.post<ChipVirgemListDto>(`${this.baseApi}/chips-virgens`, payload);
  }

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

  getControleRecebidos(opts: {
    ano?: number | string | null;
    isResumo?: boolean | string | null;
    search?: string;
    page?: number;
    pageSize?: number;
    sortBy?: string;
    sortDir?: SortDir;
  }): Observable<PagedResult<ControleRecebidoListDto>> {
    let params = new HttpParams();
    const ano = opts.ano ?? '';
    const resumo = opts.isResumo ?? '';

    if (String(ano).trim()) params = params.set('ano', String(ano).trim());
    if (String(resumo).trim()) params = params.set('isResumo', String(resumo).trim());
    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 ?? 'ano').trim());
    params = params.set('sortDir', opts.sortDir ?? 'asc');

    return this.http.get<PagedResult<ControleRecebidoListDto>>(`${this.baseApi}/controle-recebidos`, { params });
  }

  getControleRecebidoById(id: string): Observable<ControleRecebidoListDto> {
    return this.http.get<ControleRecebidoListDto>(`${this.baseApi}/controle-recebidos/${id}`);
  }

  updateControleRecebido(id: string, payload: UpdateControleRecebidoRequest): Observable<void> {
    return this.http.put<void>(`${this.baseApi}/controle-recebidos/${id}`, payload);
  }

  createControleRecebido(payload: CreateControleRecebidoRequest): Observable<ControleRecebidoListDto> {
    return this.http.post<ControleRecebidoListDto>(`${this.baseApi}/controle-recebidos`, payload);
  }

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