import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { map, tap } from 'rxjs/operators';
import { environment } from 'src/environments/environment';
import { CategoryCustomer } from '../models/category.customer.model';
import { Customer } from '../models/customer.model';
import { ResultApi } from '../models/result-api.model';
import { SubCategoryCustomer } from '../models/sub-category-customer.model';

@Injectable({
  providedIn: 'root'
})
export class CustomerService {
  public loading = false;

  constructor(private http: HttpClient) { }

  getCustomerByQuery(field: string, textSearch: string) {
    let url = environment.url + `customer?`;
    url += `&field=${field}`;
    url += `&textsearch=${textSearch}`;

    try {
      this.loading = true;
      return this.http.get<ResultApi>(url).pipe(
        map((response) => {
          console.log(response);
          return response.data;
        }),
        tap(() => (this.loading = false))
      );
    } catch (e) {
      console.log('Erro ao consultar clientes');
      console.log(e);
    }
  }

  getCustomer(name: string) {
    const url = environment.url + `customer/${name}`;

    try {
      this.loading = true;
      return this.http.get<ResultApi>(url).pipe(
        map((response) => {
          return response.data;
        }),
        tap(() => (this.loading = false))
      );
    } catch (e) {
      console.log('Erro ao consultar clientes');
      console.log(e);
    }
  }

  getCustomerbyCpf(cpf: string) {
    const url = environment.url + `customer/cpf/${cpf}`;
    try {
      return this.http.get<ResultApi>(url).pipe(
        map((response) => {
          console.log(response);
          return response;
        })
      );
    } catch (e) {
      console.log('Erro ao consultar cliente');
      console.log(e);
    }
  }

  createCustomer(customer: Customer) {
    const url = environment.url + 'customer/create';
    try {
      this.loading = true;
      return this.http.post<ResultApi>(url, customer)
        .pipe(
          map((response) => {
            console.log(response);
            return response;
          }),
          tap(() => (this.loading = false))
        );
    } catch (e) {
      console.log('Erro ao cadastrar cliente');
      console.log(e);
    }
  }

  getCategory() {
    const url = environment.url + 'customer/categories/fechall';
    return this.http.get<CategoryCustomer[]>(url);
  }

  getSubCategory() {
    const url = environment.url + 'customer/subcategories/fechall';
    return this.http.get<SubCategoryCustomer[]>(url);
  }

}
