import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:supabase_flutter/supabase_flutter.dart';

import '../models/user_office.dart';
import 'supabase_provider.dart';
import 'stream_recovery.dart';
import 'realtime_controller.dart';

final userOfficesProvider = StreamProvider<List<UserOffice>>((ref) {
  final client = ref.watch(supabaseClientProvider);

  final wrapper = StreamRecoveryWrapper<UserOffice>(
    stream: client
        .from('user_offices')
        .stream(primaryKey: ['user_id', 'office_id'])
        .order('created_at'),
    onPollData: () async {
      final data = await client
          .from('user_offices')
          .select()
          .order('created_at');
      return data.map(UserOffice.fromMap).toList();
    },
    fromMap: UserOffice.fromMap,
    channelName: 'user_offices',
    onStatusChanged: ref.read(realtimeControllerProvider).handleChannelStatus,
  );

  ref.onDispose(wrapper.dispose);
  return wrapper.stream.map((result) => result.data);
});

final userOfficesControllerProvider = Provider<UserOfficesController>((ref) {
  final client = ref.watch(supabaseClientProvider);
  return UserOfficesController(client);
});

class UserOfficesController {
  UserOfficesController(this._client);

  final SupabaseClient _client;

  Future<void> assignUserOffice({
    required String userId,
    required String officeId,
  }) async {
    await _client.from('user_offices').insert({
      'user_id': userId,
      'office_id': officeId,
    });
  }

  Future<void> removeUserOffice({
    required String userId,
    required String officeId,
  }) async {
    await _client
        .from('user_offices')
        .delete()
        .eq('user_id', userId)
        .eq('office_id', officeId);
  }
}
