import 'package:dio/dio.dart';
import 'package:superport/data/datasources/remote/api_client.dart';
import 'package:superport/data/models/auth/login_response.dart';
import 'package:superport/data/models/auth/auth_user.dart';

/// 테스트용 인증 서비스
/// 
/// FlutterSecureStorage를 사용하지 않고 메모리에 토큰을 저장합니다.
class TestAuthService {
  final ApiClient apiClient;
  
  String? _accessToken;
  String? _refreshToken;
  AuthUser? _currentUser;
  
  TestAuthService({
    required this.apiClient,
  });
  
  String? get accessToken => _accessToken;
  String? get refreshToken => _refreshToken;
  AuthUser? get currentUser => _currentUser;
  
  /// 로그인
  Future<LoginResponse> login(String email, String password) async {
    // debugPrint('[TestAuthService] 로그인 시도: $email');
    
    try {
      final response = await apiClient.dio.post(
        '/auth/login',
        data: {
          'email': email,
          'password': password,
        },
      );
      
      if (response.statusCode == 200 && response.data['success'] == true) {
        final data = response.data['data'];
        
        // 토큰 저장 (언더스코어 형식)
        _accessToken = data['access_token'];
        _refreshToken = data['refresh_token'];
        
        // 사용자 정보 저장
        _currentUser = AuthUser(
          id: data['user']['id'],
          username: data['user']['username'] ?? '',
          email: data['user']['email'],
          name: data['user']['name'] ?? '',
          role: data['user']['role'] ?? 'staff',
        );
        
        // API 클라이언트에 토큰 설정
        apiClient.updateAuthToken(_accessToken!);
        
        // debugPrint('[TestAuthService] 로그인 성공!');
        // debugPrint('[TestAuthService] - User: ${_currentUser?.email}');
        // debugPrint('[TestAuthService] - Role: ${_currentUser?.role}');
        
        // LoginResponse 반환
        return LoginResponse(
          accessToken: _accessToken!,
          refreshToken: _refreshToken!,
          tokenType: data['token_type'] ?? 'Bearer',
          expiresIn: data['expires_in'] ?? 3600,
          user: _currentUser!,
        );
      } else {
        throw Exception('로그인 실패: ${response.data['error']?['message'] ?? '알 수 없는 오류'}');
      }
    } on DioException catch (e) {
      // debugPrint('[TestAuthService] DioException: ${e.type}');
      if (e.response != null) {
        // debugPrint('[TestAuthService] Response: ${e.response?.data}');
        throw Exception('로그인 실패: ${e.response?.data['error']?['message'] ?? e.message}');
      }
      throw Exception('로그인 실패: 네트워크 오류');
    } catch (e) {
      // debugPrint('[TestAuthService] 예외 발생: $e');
      throw Exception('로그인 실패: $e');
    }
  }
  
  /// 로그아웃
  Future<void> logout() async {
    _accessToken = null;
    _refreshToken = null;
    _currentUser = null;
    apiClient.removeAuthToken();
  }
  
  /// 토큰 갱신
  Future<void> refreshAccessToken() async {
    if (_refreshToken == null) {
      throw Exception('리프레시 토큰이 없습니다');
    }
    
    try {
      final response = await apiClient.dio.post(
        '/auth/refresh',
        data: {
          'refreshToken': _refreshToken,
        },
      );
      
      if (response.statusCode == 200) {
        _accessToken = response.data['data']['accessToken'];
        _refreshToken = response.data['data']['refreshToken'];
        
        // 새 토큰으로 업데이트
        apiClient.updateAuthToken(_accessToken!);
      }
    } catch (e) {
      throw Exception('토큰 갱신 실패: $e');
    }
  }
}

/// 테스트용 인증 헬퍼
class TestAuthHelper {
  static TestAuthService? _instance;
  
  static TestAuthService getInstance(ApiClient apiClient) {
    _instance ??= TestAuthService(apiClient: apiClient);
    return _instance!;
  }
  
  static void clearInstance() {
    _instance = null;
  }
}