import 'dart:convert';

import 'package:http/http.dart' as http;
import 'package:qrscanner/config/api_config.dart';
import 'package:qrscanner/models/auth_session.dart';
import 'package:qrscanner/models/login_response.dart';
import 'package:shared_preferences/shared_preferences.dart';

class AuthService {
  static const _sessionKey = 'auth_session';

  AuthSession? _currentSession;

  AuthSession? get currentSession => _currentSession;

  Future<LoginResponse> login({
    required String username,
    required String password,
    bool rememberMe = false,
  }) async {
    final response = await http.post(
      Uri.parse(ApiConfig.loginUrl),
      headers: const {'Content-Type': 'application/json'},
      body: jsonEncode({
        'username': username,
        'password': password,
      }),
    );

    final Map<String, dynamic> body =
        jsonDecode(response.body) as Map<String, dynamic>;
    final loginResponse = LoginResponse.fromJson(body);

    if (response.statusCode == 200 &&
        loginResponse.success &&
        loginResponse.accessToken != null) {
      final session = AuthSession.fromLoginResponse(
        loginResponse.copyWith(username: loginResponse.username ?? username),
      );
      _currentSession = session;

      if (rememberMe) {
        await _saveSession(session);
      } else {
        await clearSession();
      }

      return loginResponse;
    }

    return LoginResponse(
      success: false,
      message: loginResponse.message ??
          'No se pudo iniciar sesión (${response.statusCode})',
    );
  }

  Future<void> _saveSession(AuthSession session) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_sessionKey, jsonEncode(session.toJson()));
  }

  Future<void> clearSession() async {
    _currentSession = null;
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_sessionKey);
  }

  Future<AuthSession?> loadStoredSession() async {
    final prefs = await SharedPreferences.getInstance();
    final raw = prefs.getString(_sessionKey);
    if (raw == null || raw.isEmpty) return null;

    final session = AuthSession.fromJson(
      jsonDecode(raw) as Map<String, dynamic>,
    );
    _currentSession = session;
    return session;
  }

  Future<bool> hasStoredSession() async {
    final session = await loadStoredSession();
    return session != null && session.accessToken.isNotEmpty;
  }
}