import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import '../../domain/entities/auth_user.dart';
import '../../domain/repositories/auth_repository.dart';
import '../datasources/auth_remote_datasource.dart';

const _keyAccessToken = 'access_token';
const _keyRefreshToken = 'refresh_token';

class AuthRepositoryImpl implements AuthRepository {
  final AuthRemoteDatasource _remoteDatasource;
  final FlutterSecureStorage _secureStorage;

  AuthRepositoryImpl({
    required AuthRemoteDatasource remoteDatasource,
    required FlutterSecureStorage secureStorage,
  })  : _remoteDatasource = remoteDatasource,
        _secureStorage = secureStorage;

  @override
  Future<AuthUserEntity> login({
    required String email,
    required String password,
  }) async {
    final response = await _remoteDatasource.login(
      email: email,
      password: password,
    );

    // Store tokens securely
    await _secureStorage.write(key: _keyAccessToken, value: response.accessToken);
    await _secureStorage.write(key: _keyRefreshToken, value: response.refreshToken);

    return AuthUserEntity(
      id: response.user.id,
      email: response.user.email,
      name: response.user.name,
      roles: response.user.roles,
    );
  }

  @override
  Future<void> logout() async {
    await _secureStorage.delete(key: _keyAccessToken);
    await _secureStorage.delete(key: _keyRefreshToken);
  }

  @override
  Future<bool> refreshToken() async {
    try {
      final refreshToken = await _secureStorage.read(key: _keyRefreshToken);
      if (refreshToken == null) return false;

      final data = await _remoteDatasource.refreshToken(refreshToken);

      await _secureStorage.write(
        key: _keyAccessToken,
        value: data['accessToken'] as String,
      );
      await _secureStorage.write(
        key: _keyRefreshToken,
        value: data['refreshToken'] as String,
      );

      return true;
    } catch (_) {
      await logout();
      return false;
    }
  }

  @override
  Future<AuthUserEntity?> getCurrentUser() async {
    try {
      final accessToken = await _secureStorage.read(key: _keyAccessToken);
      if (accessToken == null) return null;

      final user = await _remoteDatasource.getProfile(accessToken);
      return AuthUserEntity(
        id: user.id,
        email: user.email,
        name: user.name,
        roles: user.roles,
      );
    } catch (_) {
      return null;
    }
  }

  @override
  Future<bool> isAuthenticated() async {
    final token = await _secureStorage.read(key: _keyAccessToken);
    return token != null;
  }
}
