import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:flux/features/settings/document_sequence/models/document_sequence_model.dart';
import 'package:get_it/get_it.dart';
import 'package:supabase_flutter/supabase_flutter.dart';

class DocumentSequenceRepository {
  final _supabase = GetIt.I.get<SupabaseClient>();
  final _companyId = GetIt.I.get<SessionCubit>().state.company!.id!;

  Future<List<DocumentSequence>> getDocumentSequences() async {
    try {
      final response = await _supabase
          .from(Tables.documentSequences)
          .select()
          .eq('company_id', _companyId);

      return (response as List)
          .map((e) => DocumentSequence.fromMap(e))
          .toList();
    } catch (e) {
      throw ('Errore durante il caricamento delle sequenze: $e');
    }
  }

  Future<String> getNextDocumentNumber(String docType) async {
    try {
      // Chiamiamo la funzione SQL che abbiamo appena creato!
      final response = await _supabase.rpc(
        'get_next_sequence',
        params: {'p_doc_type': docType},
      );
      return response as String;
    } catch (e) {
      throw ('Errore durante la generazione del numero: $e');
    }
  }

  Future<void> createOrUpdateSequence({
    required DocumentSequence sequence,
  }) async {
    try {
      await _supabase.from(Tables.documentSequences).upsert({
        'company_id': _companyId,
        'doc_type': sequence.docType,
        'next_value': sequence.nextValue,
        'prefix': sequence.prefix,
      });
    } on Exception catch (e) {
      throw ('Errore durante la creazione/aggiornamento della sequenza: $e');
    }
  }

  Future<void> updateSequence({required DocumentSequence sequence}) async {
    await _supabase.from(Tables.documentSequences).upsert({
      'company_id': _companyId,
      'doc_type': sequence.docType,
      'next_value': sequence.nextValue,
      'prefix': sequence.prefix,
    });
  }
}
