import 'dart:typed_data';

import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import '../models/company_model.dart';

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

  Future<CompanyModel> createCompany(CompanyModel company) async {
    try {
      // .select().single() trasforma la risposta nell'oggetto appena inserito
      final response = await _supabase
          .from(Tables.companies)
          .insert(company.toMap())
          .select()
          .single();

      return CompanyModel.fromMap(response);
    } on PostgrestException catch (e) {
      throw e.message;
    } catch (e) {
      throw e.toString();
    }
  }

  Future<CompanyModel> updateCompany(CompanyModel company) async {
    try {
      final response = await _supabase
          .from(Tables.companies)
          .update(company.toMap())
          .eq('id', company.id!)
          .select()
          .single();

      return CompanyModel.fromMap(response);
    } on PostgrestException catch (e) {
      throw e.message;
    } catch (e) {
      throw e.toString();
    }
  }

  Future<String> uploadCompanyLogo({
    required String companyId,
    required Uint8List fileBytes,
    required String fileName,
  }) async {
    try {
      // 1. Prepariamo il path.
      // Organizziamo per companyId e aggiungiamo un timestamp per evitare cache del browser
      // quando l'utente cambia logo più volte.
      final extension = fileName.split('.').last;
      final timestamp = DateTime.now().millisecondsSinceEpoch;
      final filePath = '$companyId/logo_$timestamp.$extension';

      // 2. Caricamento fisico dei bytes
      // Usiamo uploadBinary che è perfetto per Uint8List
      await _supabase.storage
          .from('company_logos')
          .uploadBinary(
            filePath,
            fileBytes,
            fileOptions: const FileOptions(
              cacheControl: '3600',
              upsert:
                  true, // Se esiste già un file con lo stesso nome, lo sovrascrive
            ),
          );

      // 3. Otteniamo l'URL pubblico.
      // Nota: il bucket 'company_logos' deve essere impostato come PUBLIC su Supabase
      final String publicUrl = _supabase.storage
          .from('company_logos')
          .getPublicUrl(filePath);

      return publicUrl;
    } catch (e) {
      throw Exception("Errore durante l'upload del logo: $e");
    }
  }

  Future<CompanyModel?> getCompany() async {
    try {
      final userId = _supabase.auth.currentUser?.id;
      final response = await _supabase
          .from(Tables.companies)
          .select()
          .eq('user_id', userId as Object)
          .maybeSingle();

      return response != null ? CompanyModel.fromMap(response) : null;
    } catch (e) {
      return null;
    }
  }
}
