import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { throwError } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import { environment } from 'src/environments/environment';
import { CustomerAddress } from '../models/customer-address.model';
import { ResultApi } from '../models/result-api.model';

@Injectable({
  providedIn: 'root'
})
export class AddressCustomerService {

  constructor(private http: HttpClient) { }

  getAddress(customerId: number) {
    const url = environment.url + `address/${customerId}`;

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

  getAddressByCep(customerId: number, cep: string) {
    const url = environment.url + `address/cep/${customerId}/${cep}`;
    return this.http.get<any>(url).pipe(
      map((response) => {
        console.log(response);
        return response;
      })
    );
  }

  createAddress(customer: CustomerAddress) {
    const url = environment.url + 'address/create';
    return this.http.post<ResultApi>(url, customer)
      .pipe(
        map((response) => {
          return response;
        }),
        catchError(err => {
          return throwError(err);
        })
      );
  }
}
