import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart';
import '../models/user_profile_model.dart';
import 'package:descope/descope.dart';

class ProfileRepository {
  static String _envOrDefault(String key, String fallback) {
    if (!dotenv.isInitialized) {
      return fallback;
    }
    return dotenv.env[key] ?? fallback;
  }

  static String get _baseUrl => _envOrDefault('BACKEND_URL', 'https://sso.hmac.kr');

  // Helper to get session token
  static Future<String?> _getToken() async {
    final session = await Descope.sessionManager.session;
    return session?.sessionToken.jwt;
  }

  Future<UserProfile> getMyProfile() async {
    final token = await _getToken();
    if (token == null) throw Exception('No active session');

    final url = Uri.parse('$_baseUrl/api/v1/user/me');
    final response = await http.get(
      url,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer $token',
      },
    );

    if (response.statusCode == 200) {
      return UserProfile.fromJson(jsonDecode(response.body));
    } else {
      throw Exception('Failed to load profile: ${response.body}');
    }
  }

  Future<void> updateMyProfile({
    required String name,
    required String phone,
    required String department,
  }) async {
    final token = await _getToken();
    if (token == null) throw Exception('No active session');

    final url = Uri.parse('$_baseUrl/api/v1/user/me');
    final response = await http.put(
      url,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer $token',
      },
      body: jsonEncode({
        'name': name,
        'phone': phone,
        'department': department,
      }),
    );

    if (response.statusCode != 200) {
      throw Exception('Failed to update profile: ${response.body}');
    }
  }

  Future<void> sendUpdateCode(String phone) async {
    final token = await _getToken();
    if (token == null) throw Exception('No active session');

    final url = Uri.parse('$_baseUrl/api/v1/user/me/send-code');
    final response = await http.post(
      url,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer $token',
      },
      body: jsonEncode({'phone': phone}),
    );

    if (response.statusCode != 200) {
      throw Exception('인증번호 전송 실패: ${response.body}');
    }
  }

  Future<void> verifyUpdateCode(String phone, String code) async {
    final token = await _getToken();
    if (token == null) throw Exception('No active session');

    final url = Uri.parse('$_baseUrl/api/v1/user/me/verify-code');
    final response = await http.post(
      url,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer $token',
      },
      body: jsonEncode({'phone': phone, 'code': code}),
    );

    if (response.statusCode != 200) {
      throw Exception('인증 실패: ${response.body}');
    }
  }
}
