import 'package:flutter_riverpod/flutter_riverpod.dart';

import 'supabase_provider.dart';
import 'stream_recovery.dart';
import 'realtime_controller.dart';
import '../models/team.dart';
import '../models/team_member.dart';

/// Real-time stream of teams with automatic recovery and graceful degradation.
final teamsProvider = StreamProvider<List<Team>>((ref) {
  final client = ref.watch(supabaseClientProvider);

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

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

/// Real-time stream of team membership rows with automatic recovery.
final teamMembersProvider = StreamProvider<List<TeamMember>>((ref) {
  final client = ref.watch(supabaseClientProvider);

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

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