import 'dart:convert';

import 'package:allen/services/storage_service.dart';
import 'package:http/http.dart' as http;

import '../models/user.dart';
import '../secrets.dart';

class ApiService {
  static Future<Map<String, dynamic>> login(
      String email, String password) async {
    final response = await http.post(
      Uri.parse('$baseUrl/console/api/login/'),
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      },
      body: jsonEncode({
        'email': email,
        'password': password,
      }),
    );

    return jsonDecode(response.body);
  }

  Future<String> getWorkbenchToken(String appId) async {
    try {
      User? user = await StorageService.getUser();
      String token = user?.token ?? '';
      final response = await http.post(
        Uri.parse('$baseUrl/console/api/apps/workbench'),
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Bearer $token',
        },
        body: jsonEncode({
          'app_id': appId,
        }),
      );

      if (response.statusCode == 200) {
        return jsonDecode(response.body)['data'];
      }

      throw Exception('获取会话token失败');
    } catch (e) {
      throw Exception('获取会话token失败: $e');
    }
  }
}
