import 'dart:convert';
import 'dart:io';

import 'package:app_gaslieferung/dto/fail_response_dto.dart';
import 'package:app_gaslieferung/dto/get_deliveries_dto.dart';
import 'package:app_gaslieferung/exceptions/login.dart';
import 'package:app_gaslieferung/exceptions/server.dart';
import 'package:app_gaslieferung/model/tour.dart';
import 'package:http/http.dart' as http;

class TourService {
  final String baseUrl;

  TourService({required this.baseUrl});

  Future<GetDeliveriesDTO> getCars(String sessionId) async {
    final response = await http.get(
      Uri.parse('$baseUrl/cars'),
      headers: {'Cookie': 'session_id=$sessionId'},
    );

    int statusCode = response.statusCode;
    if (statusCode == HttpStatus.unauthorized) {
      throw LoginUnauthorizedException();
    } else if (statusCode != HttpStatus.ok) {
      final dto = FailResponseDTO.fromJson(jsonDecode(response.body));
      throw ServerErrorException(message: dto.message);
    }

    return GetDeliveriesDTO.fromJson(jsonDecode(response.body));
  }

  Future<Tour> getTour(String sessionId, String carId) async {
    final response = await http.get(
      Uri.parse('$baseUrl/tour/$carId'),
      headers: {'Cookie': 'session_id=$sessionId'},
    );

    int statusCode = response.statusCode;
    if (statusCode == HttpStatus.unauthorized) {
      throw LoginUnauthorizedException();
    } else if (statusCode != HttpStatus.ok) {
      final dto = FailResponseDTO.fromJson(jsonDecode(response.body));
      throw ServerErrorException(message: dto.message);
    }

    return Tour.fromJson(jsonDecode(response.body));
  }
}