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

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

final userOfficesProvider = StreamProvider<List<UserOffice>>((ref) {
  final client = ref.watch(supabaseClientProvider);
  return client
      .from('user_offices')
      .stream(primaryKey: ['user_id', 'office_id'])
      .order('created_at')
      .map((rows) => rows.map(UserOffice.fromMap).toList());
});

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);
  }
}
