import 'dart:convert';
import 'package:userfront/i18n.dart';
import '../models/user_profile_model.dart';
import '../../../../core/services/auth_token_store.dart';
import '../../../../core/services/http_client.dart';
import '../../../../core/services/runtime_env.dart';

class ProfileRepository {
  static String get _baseUrl => runtimeBackendUrl();

  // Helper to get session token
  static Future<String?> _getToken() async {
    return AuthTokenStore.getToken();
  }

  Future<UserProfile> getMyProfile() async {
    final token = await _getToken();
    final useCookie = AuthTokenStore.usesCookie();
    if (token == null && !useCookie) {
      throw Exception(tr('err.userfront.session.missing'));
    }

    final url = Uri.parse('$_baseUrl/api/v1/user/me');
    final client = createHttpClient(withCredentials: useCookie);
    final headers = <String, String>{'Content-Type': 'application/json'};
    if (!useCookie && token != null) {
      headers['Authorization'] = 'Bearer $token';
    }
    final response = await client.get(url, headers: headers);
    client.close();

    if (response.statusCode == 200) {
      return UserProfile.fromJson(jsonDecode(response.body));
    } else {
      throw Exception(
        tr(
          'err.userfront.profile.load_failed',
          params: {'error': response.body},
        ),
      );
    }
  }

  Future<void> updateMyProfile({
    required String name,
    required String phone,
    required String department,
  }) async {
    final token = await _getToken();
    final useCookie = AuthTokenStore.usesCookie();
    if (token == null && !useCookie) {
      throw Exception(tr('err.userfront.session.missing'));
    }

    final url = Uri.parse('$_baseUrl/api/v1/user/me');
    final client = createHttpClient(withCredentials: useCookie);
    final headers = <String, String>{'Content-Type': 'application/json'};
    if (!useCookie && token != null) {
      headers['Authorization'] = 'Bearer $token';
    }
    final response = await client.put(
      url,
      headers: headers,
      body: jsonEncode({
        'name': name,
        'phone': phone,
        'department': department,
      }),
    );
    client.close();

    if (response.statusCode != 200) {
      throw Exception(
        tr(
          'err.userfront.profile.update_failed',
          params: {'error': response.body},
        ),
      );
    }
  }

  Future<void> sendUpdateCode(String phone) async {
    final token = await _getToken();
    final useCookie = AuthTokenStore.usesCookie();
    if (token == null && !useCookie) {
      throw Exception(tr('err.userfront.session.missing'));
    }

    final url = Uri.parse('$_baseUrl/api/v1/user/me/send-code');
    final client = createHttpClient(withCredentials: useCookie);
    final headers = <String, String>{'Content-Type': 'application/json'};
    if (!useCookie && token != null) {
      headers['Authorization'] = 'Bearer $token';
    }
    final response = await client.post(
      url,
      headers: headers,
      body: jsonEncode({'phone': phone}),
    );
    client.close();

    if (response.statusCode != 200) {
      throw Exception(
        tr(
          'err.userfront.profile.send_code_failed',
          params: {'error': response.body},
        ),
      );
    }
  }

  Future<void> changePassword({
    required String currentPassword,
    required String newPassword,
  }) async {
    final token = await _getToken();
    final useCookie = AuthTokenStore.usesCookie();
    if (token == null && !useCookie) {
      throw Exception(tr('err.userfront.session.missing'));
    }

    final url = Uri.parse('$_baseUrl/api/v1/user/me/password');
    final client = createHttpClient(withCredentials: useCookie);
    final headers = <String, String>{'Content-Type': 'application/json'};
    if (!useCookie && token != null) {
      headers['Authorization'] = 'Bearer $token';
    }
    final response = await client.post(
      url,
      headers: headers,
      body: jsonEncode({
        'currentPassword': currentPassword,
        'newPassword': newPassword,
      }),
    );
    client.close();

    if (response.statusCode != 200) {
      throw Exception(
        tr(
          'err.userfront.profile.password_change_failed',
          params: {'error': response.body},
        ),
      );
    }
  }

  Future<void> verifyUpdateCode(String phone, String code) async {
    final token = await _getToken();
    final useCookie = AuthTokenStore.usesCookie();
    if (token == null && !useCookie) {
      throw Exception(tr('err.userfront.session.missing'));
    }

    final url = Uri.parse('$_baseUrl/api/v1/user/me/verify-code');
    final client = createHttpClient(withCredentials: useCookie);
    final headers = <String, String>{'Content-Type': 'application/json'};
    if (!useCookie && token != null) {
      headers['Authorization'] = 'Bearer $token';
    }
    final response = await client.post(
      url,
      headers: headers,
      body: jsonEncode({'phone': phone, 'code': code}),
    );
    client.close();

    if (response.statusCode != 200) {
      throw Exception(
        tr(
          'err.userfront.profile.verify_code_failed',
          params: {'error': response.body},
        ),
      );
    }
  }
}
