import 'dart:convert';

import 'package:http/http.dart' as http;

class Profile {
  final String name;
  const Profile(this.name);
  
  factory Profile.fromJson(Map<String, dynamic> json) {
    return switch(json) {
      {'name': String name} => Profile(name),
      _ => throw const FormatException('Invalid profile object.')
    };
  }
}

Future<List<Profile>> getProfiles(String token) async {
  final http.Response response = await http.get(
    Uri.parse('http://localhost:8080/api/profiles'),
    headers: {
      'Authorization': 'Bearer $token'
    }
  );
  if (response.statusCode == 200) {
    if (jsonDecode(response.body) == null) return []; // Workaround for bad array serialization in the API.
    final data = jsonDecode(response.body) as List<dynamic>;
    return data.map((obj) => Profile.fromJson(obj)).toList();
  } else {
    throw Exception('Failed to get profiles.');
  }
}

Future<void> deleteProfile(String token, Profile profile) async {
  final http.Response response = await http.delete(
    Uri.parse('http://localhost:8080/api/profiles/${profile.name}'),
    headers: {
      'Authorization': 'Bearer $token'
    }
  );
  if (response.statusCode != 200) {
    throw Exception('Failed to delete profile ${profile.name}');
  }
}
