import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart';
import '../models/price_data.dart';

class ApiService {
  final String baseUrl;

  ApiService() : baseUrl = dotenv.env['API_URL'] ?? 'http://localhost:3000' {
    // Debug: Print the actual URL being used
    if (kDebugMode) {
      print('ApiService initialized with baseUrl: $baseUrl');
      print('Available env vars: ${dotenv.env.keys.toList()}');
    }
  }

  Future<LatestPrice?> fetchLatestPrice() async {
    try {
      final url = '$baseUrl/prices/latest';
      if (kDebugMode) {
        print('Fetching latest price from: $url');
      }
      
      final response = await http.get(Uri.parse(url));
      
      if (kDebugMode) {
        print('Response status: ${response.statusCode}');
        print('Response body: ${response.body}');
      }
      
      if (response.statusCode == 200) {
        final data = jsonDecode(response.body) as Map<String, dynamic>;
        return LatestPrice.fromJson(data);
      } else {
        if (kDebugMode) {
          print('HTTP Error ${response.statusCode}: ${response.body}');
        }
      }
    } catch (e) {
      if (kDebugMode) {
        print('Error fetching latest price: $e');
      }
    }
    return null;
  }

  Future<HistoryData?> fetchHistory(String range) async {
    try {
      final url = '$baseUrl/index/history?range=$range';
      if (kDebugMode) {
        print('Fetching history from: $url');
      }
      
      final response = await http.get(Uri.parse(url));
      
      if (kDebugMode) {
        print('History response status: ${response.statusCode}');
      }
      
      if (response.statusCode == 200) {
        final data = jsonDecode(response.body) as Map<String, dynamic>;
        return HistoryData.fromJson(data);
      } else {
        if (kDebugMode) {
          print('HTTP Error ${response.statusCode}: ${response.body}');
        }
      }
    } catch (e) {
      if (kDebugMode) {
        print('Error fetching history: $e');
      }
    }
    return null;
  }
}
