import { supabase } from '@/config/supabase';

export const resourceService = {
  async getResources({ page = 1, pageSize = 10, orderBy = 'created_at', ascending = false, searchQuery = '', type = '' }) {
    try {
      let query = supabase
        .from('resources')
        .select('*', { count: 'exact' })
        .eq('type', type)

      if (searchQuery) {
        query = query.or(`external_id.ilike.%${searchQuery}%`);
      }
      if (orderBy) {
        query = query.order(orderBy, { ascending });
      }
      const from = (page - 1) * pageSize;
      query = query.range(from, from + pageSize - 1);

      const { data, count, error } = await query;
      if (error) throw error;

      return {
        data,
        total: count || 0,
      };
    } catch (error) {
      throw error;
    }
  },

  async createResource(values) {
    try {
      const { data, error } = await supabase
        .from('resources')
        .insert([{
          ...values,
          type: 'quota',
          created_at: new Date().toISOString(),
          updated_at: new Date().toISOString(),
        }])
        .select()
        .single();

      if (error) throw error;
      return data;
    } catch (error) {
      throw error;
    }
  },

  async updateResource(id, values) {
    try {
      const { data, error } = await supabase
        .from('resources')
        .update({
          ...values,
          updated_at: new Date().toISOString(),
        })
        .eq('id', id)
        .eq('type', 'quota')
        .select()
        .single();

      if (error) throw error;
      return data;
    } catch (error) {
      throw error;
    }
  },

  async deleteResource(id,type) {
    try {
      const { error } = await supabase
        .from('resources')
        .delete()
        .eq('id', id)
        .eq('type', type)
        .select()

      if (error) throw error;
      return true;
    } catch (error) {
      throw error;
    }
  },
};