import 'dart:convert'; import 'package:http/http.dart' as http; import '../models/action_template.dart'; import '../../core/constants/api_constants.dart'; /// Service for fetching action templates and categories /// Used by ActionPickerDialog to show available actions class ActionTemplateService { final String baseUrl; final String? authToken; ActionTemplateService({ required this.baseUrl, this.authToken, }); Map get _headers => { 'Content-Type': 'application/json', if (authToken != null) 'Authorization': 'Bearer $authToken', }; /// Fetch all action categories Future getActionCategories() async { final url = '$baseUrl/api/v1/configuration/action-categories'; final response = await http.get( Uri.parse(url), headers: _headers, ); if (response.statusCode == 200) { final json = jsonDecode(response.body) as Map; return ActionCategoriesResponse.fromJson(json); } else { throw Exception('Failed to load action categories: ${response.statusCode}'); } } /// Fetch all action templates Future> getActionTemplates() async { final url = '$baseUrl/api/v1/configuration/action-types'; final response = await http.get( Uri.parse(url), headers: _headers, ); if (response.statusCode == 200) { final json = jsonDecode(response.body) as Map; final actionTypesMap = json['action_types'] as Map; return actionTypesMap.map((key, value) { final templateJson = value as Map; templateJson['action_name'] = key; // Add action name to the template return MapEntry(key, ActionTemplate.fromJson(templateJson)); }); } else { throw Exception('Failed to load action templates: ${response.statusCode}'); } } /// Fetch a specific action template by name Future getActionTemplate(String actionName) async { final url = '$baseUrl/api/v1/configuration/action-types/$actionName'; final response = await http.get( Uri.parse(url), headers: _headers, ); if (response.statusCode == 200) { final json = jsonDecode(response.body) as Map; return ActionTemplate.fromJson(json); } else if (response.statusCode == 404) { throw Exception('Action template "$actionName" not found'); } else { throw Exception('Failed to load action template: ${response.statusCode}'); } } }