import 'package:supabase_flutter/supabase_flutter.dart';
import '../models/game_model.dart';

class GameController {
  final _supabase = Supabase.instance.client;

  // 1. LER JOGOS (Com Filtros Opcionais)
  Stream<List<Game>> getFilteredGames({String? teamFilter, String? seasonFilter}) {
    return _supabase
        .from('games') 
        .stream(primaryKey: ['id'])
        .asyncMap((event) async {
          
          // 👇 A CORREÇÃO ESTÁ AQUI: Lê diretamente da tabela 'games'
          var query = _supabase.from('games').select();

          // Aplica o filtro de Temporada
          if (seasonFilter != null && seasonFilter.isNotEmpty && seasonFilter != 'Todas') {
            query = query.eq('season', seasonFilter);
          }

          // Aplica o filtro de Equipa (Procura em casa ou fora)
          if (teamFilter != null && teamFilter.isNotEmpty && teamFilter != 'Todas') {
            query = query.or('my_team.eq.$teamFilter,opponent_team.eq.$teamFilter');
          }

          // Executa a query com a ordenação por data
          final viewData = await query.order('game_date', ascending: false);
              
          return viewData.map((json) => Game.fromMap(json)).toList();
        });
  }

  // 2. CRIAR JOGO
  Future<String?> createGame(String myTeam, String opponent, String season) async {
    try {
      final response = await _supabase.from('games').insert({
        'my_team': myTeam,
        'opponent_team': opponent,
        'season': season,
        'my_score': 0,
        'opponent_score': 0,
        'status': 'Decorrer', 
        'game_date': DateTime.now().toIso8601String(),
      }).select().single(); 

      return response['id']; 
    } catch (e) {
      print("Erro ao criar jogo: $e");
      return null;
    }
  }

  void dispose() {}
}