import 'dart:developer';

import 'package:supabase_flutter/supabase_flutter.dart';
import 'package:uuid/uuid.dart';

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

  Future<List> getList() async {
    List<Map<String, dynamic>> stockData = [];

    final data = await _supabase.from('stocks').select('*');
    stockData = data;

    List<Map<String, dynamic>> result = [];

    for (var stock in stockData) {
      final muuid = stock['ref_medicines_uuid'];

      try {
        final medicineNameResult =
            await _supabase.from('ref_medicines').select('medicine_name').eq('ref_medicines_uuid', muuid);

        if (medicineNameResult.isNotEmpty) {
          final medicineName = medicineNameResult[0]['medicine_name'];
          result.add({
            'medicine_name': medicineName,
            'quantity': stock['quantity'],
            'expiration_date': stock['expiration_date'],
          });
        }
      } catch (e) {
        return [];
      }
    }
    return result;
  }

  // Future<String> getUUID(String name) async {
  //   final data = await _supabase.from('ref_types').select('ref_types_uuid').eq('type_name', name);
  //   return data.first['ref_types_uuid'].toString();
  // }

  Future<void> postStock(String muuid, String name, String quantity) async {
    final uuid = Uuid().v4();

    final stock = {
      'stock_uuid': uuid,
      'ref_medicines_uuid': muuid,
      'expiration_date': name,
      'quantity': quantity,
    };

    await _supabase.from('stocks').insert(stock);
  }
}
