import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:p_tits_pas/models/relais_model.dart';
import 'package:p_tits_pas/services/api/api_config.dart';
import 'package:p_tits_pas/services/api/tokenService.dart';

class RelaisService {
  static Future<Map<String, String>> _headers() async {
    final token = await TokenService.getToken();
    return token != null
        ? ApiConfig.authHeaders(token)
        : Map<String, String>.from(ApiConfig.headers);
  }

  static String _extractError(String body, String fallback) {
    try {
      final decoded = jsonDecode(body);
      if (decoded is Map<String, dynamic>) {
        final message = decoded['message'];
        if (message is String && message.trim().isNotEmpty) {
          return message;
        }
      }
    } catch (_) {}
    return fallback;
  }

  static Future<List<RelaisModel>> getRelais() async {
    final response = await http.get(
      Uri.parse('${ApiConfig.baseUrl}${ApiConfig.relais}'),
      headers: await _headers(),
    );

    if (response.statusCode != 200) {
      throw Exception(
        _extractError(response.body, 'Erreur chargement relais'),
      );
    }

    final List<dynamic> data = jsonDecode(response.body);
    return data
        .whereType<Map<String, dynamic>>()
        .map(RelaisModel.fromJson)
        .toList();
  }

  static Future<RelaisModel> createRelais(Map<String, dynamic> payload) async {
    final response = await http.post(
      Uri.parse('${ApiConfig.baseUrl}${ApiConfig.relais}'),
      headers: await _headers(),
      body: jsonEncode(payload),
    );

    if (response.statusCode != 201 && response.statusCode != 200) {
      throw Exception(
        _extractError(response.body, 'Erreur création relais'),
      );
    }

    return RelaisModel.fromJson(
        jsonDecode(response.body) as Map<String, dynamic>);
  }

  static Future<RelaisModel> updateRelais(
    String id,
    Map<String, dynamic> payload,
  ) async {
    final response = await http.patch(
      Uri.parse('${ApiConfig.baseUrl}${ApiConfig.relais}/$id'),
      headers: await _headers(),
      body: jsonEncode(payload),
    );

    if (response.statusCode != 200) {
      throw Exception(
        _extractError(response.body, 'Erreur mise à jour relais'),
      );
    }

    return RelaisModel.fromJson(
        jsonDecode(response.body) as Map<String, dynamic>);
  }

  static Future<void> deleteRelais(String id) async {
    final response = await http.delete(
      Uri.parse('${ApiConfig.baseUrl}${ApiConfig.relais}/$id'),
      headers: await _headers(),
    );

    if (response.statusCode != 200 && response.statusCode != 204) {
      throw Exception(
        _extractError(response.body, 'Erreur suppression relais'),
      );
    }
  }
}
