import 'package:supabase_flutter/supabase_flutter.dart';

class RefMedicines {
  final SupabaseClient _supabase = Supabase.instance.client;

  Future<List> getList() async {
    try {
      final data = await _supabase
          .from('ref_medicines')
          .select('medicine_name, ref_manufactorers(manufactorer_name)')
          .order('medicine_name', ascending: true);
      return data.toList();
    } catch (e) {
      return [];
    }
  }

  Future<List> getListWithUUID() async {
    try {
      final data = await _supabase
          .from('ref_medicines')
          .select('ref_medicines_uuid, medicine_name')
          .order('medicine_name', ascending: true);
      return data.toList();
    } catch (e) {
      return [];
    }
  }

  Future<String> getUUID(String name) async {
    try {
      final data = await _supabase.from('ref_medicines').select('ref_medicines_uuid').eq('medicine_name', name);
      return data.first['ref_medicines_uuid'];
    } catch (e) {
      return '';
    }
  }

  Future<String> getBarcode(String name) async {
    try {
      final data = await _supabase.from('ref_medicines').select('barcode').eq('medicine_name', name);
      return data.first['barcode'];
    } catch (e) {
      return '';
    }
  }

  Future<bool> postMedicine(String uuid, String name, String muuid, String guuid, String tuuid, String barcode) async {
    final medicine = {
      'ref_medicines_uuid': uuid,
      'medicine_name': name,
      'ref_manufactorers_uuid': muuid,
      'ref_generic_names_uuid': guuid,
      'ref_types_uuid': tuuid,
      'barcode': barcode
    };

    try {
      await _supabase.from('ref_medicines').insert(medicine);
      return true;
    } catch (e) {
      return false;
    }
  }
}
