import 'package:get/get.dart';
import 'package:sigap/src/features/personalization/data/models/models/user_metadata_model.dart';
import 'package:supabase_flutter/supabase_flutter.dart';

class SupabaseService extends GetxService {
  static SupabaseService get instance => Get.find<SupabaseService>();

  final _client = Supabase.instance.client;

  /// Get Supabase client instance
  SupabaseClient get client => _client;

  /// Get current authenticated user
  User? get currentUser => _client.auth.currentUser;

  /// Get current user ID, if authenticated
  String? get currentUserId => _client.auth.currentUser?.id;

  /// Get type-safe user metadata
  UserMetadataModel get userMetadata {
    if (currentUser == null) return UserMetadataModel();
    return UserMetadataModel.fromJson(currentUser!.userMetadata);
  }

  /// Check if user is authenticated
  bool get isAuthenticated => currentUser != null;

  /// Check if current user is an officer based on metadata
  bool get isOfficer => userMetadata.isOfficer;

  /// Get the stored identifier (NIK or NRP) of the current user
  String? get userIdentifier {
    if (currentUser == null) return null;
    final metadata = userMetadata;

    if (metadata.isOfficer == true && metadata.officerData != null) {
      return metadata.officerData?.nrp;
    } else {
      return metadata.viewerData?.profile?.nik;
    }
  }

  /// Initialize Supabase service
  Future<SupabaseService> init() async {
    return this;
  }

  /// Update user metadata with raw Map
  Future<User?> updateUserMetadata(Map<String, dynamic> metadata) async {
    try {
      final response = await client.auth.updateUser(
        UserAttributes(data: metadata),
      );
      return response.user;
    } catch (e) {
      throw Exception('Failed to update user metadata: $e');
    }
  }

  /// Update user metadata with our model
  Future<User?> updateUserMetadataModel(UserMetadataModel metadata) async {
    try {
      final response = await client.auth.updateUser(
        UserAttributes(data: metadata.toJson()),
      );
      return response.user;
    } catch (e) {
      throw Exception('Failed to update user metadata: $e');
    }
  }

  /// Check if current user is an officer
  bool get isUserOfficer => userMetadata.isOfficer;


}
