import 'package:flutter_riverpod/flutter_riverpod.dart';

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

final servicesProvider = StreamProvider<List<Service>>((ref) {
  final client = ref.watch(supabaseClientProvider);

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

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

final servicesOnceProvider = FutureProvider<List<Service>>((ref) async {
  final client = ref.watch(supabaseClientProvider);
  final rows = await client.from('services').select().order('name');
  return (rows as List<dynamic>)
      .map((r) => Service.fromMap(r as Map<String, dynamic>))
      .toList();
});
