import 'dart:convert';

import '../data/session/session_storage.dart';
import 'package:http/http.dart' as http;

class BaseService {
  int currentPage = 0;
  int limit = 20;
  int total = 0;
  //produccion: hermogas.est.api.rdsistemas.app
  //prueba: hermogas.est.test.rdsistemas.app

  String base_url = 'https://sis.api.edesarrollos.info';
  String baseUrl = 'sis.api.edesarrollos.info';

  Future<Map<String, String>> getDefaultHeaders({withAuth = true}) async {
    Map<String, String> defaultHeaders = {'Content-Type': 'application/json'};

    if (withAuth) {
      String? token = await SessionStorage().getToken();
      defaultHeaders['Authorization'] = 'Bearer ${token ?? ''}';
    }

    return defaultHeaders;
  }

  Future<http.Response> get(String endpoint,
      {bool withAuth = true,
      Map<String, String>? queryParameters,
      Map<String, String>? headers}) async {
    final uri = Uri.https(baseUrl, endpoint, queryParameters);
    var defaultHeaders = await getDefaultHeaders(withAuth: withAuth);
    var head = {...?headers, ...defaultHeaders};
    return await http.get(uri, headers: head);
  }

  Future<http.Response> post(String endpoint,
      {bool withAuth = true,
      Map<String, String>? queryParameters,
      Map<String, dynamic>? body,
      Map<String, String>? headers}) async {
    final uri = Uri.https(baseUrl, endpoint, queryParameters);
    var defaultHeaders = await getDefaultHeaders(withAuth: withAuth);
    var head = {...?headers, ...defaultHeaders};
    return await http.post(uri, body: json.encode(body), headers: head);
  }

  Future<http.Response> delete(String endpoint,
      {bool withAuth = true,
      Map<String, String>? queryParameters,
      Map<String, dynamic>? body,
      Map<String, String>? headers}) async {
    final uri = Uri.https(baseUrl, endpoint, queryParameters);
    var defaultHeaders = await getDefaultHeaders(withAuth: withAuth);
    var head = {...?headers, ...defaultHeaders};
    return await http.delete(uri, body: json.encode(body), headers: head);
  }
}
