import 'package:drift/drift.dart';
import 'package:niogu_app/core/database/app_database.dart';
import 'package:niogu_app/core/enums/customer_source.dart';
import 'package:niogu_app/core/system/system_setting.dart';
import 'package:niogu_app/features/customer/domain/entities/customer.dart';
import 'package:niogu_app/features/customer/domain/repositories/i_customer_repository.dart';

class CustomerRepositoryImpl implements ICustomerRepository {
  final AppDatabase _appDatabase;

  const CustomerRepositoryImpl(this._appDatabase);

  @override
  Stream<List<DisplayCustomers>> watchCustomers() {
    return _appDatabase.customerDao.watchAllCustomers();
  }

  @override
  Future<CustomerDetail> fetchCustomerById(String id) async {
    return await _appDatabase.customerDao.getCustomerById(id);
  }

  @override
  Stream<List<CustomerAddress>> watchCustomerAddresses(String customerId) {
    return _appDatabase.customerDao.watchAllCustomerAddresses(customerId);
  }

  @override
  Stream<List<CustomerActivities>> watchCustomerActivities(String customerId) {
    return _appDatabase.customerDao.watchAllCustomerActivities(customerId);
  }

  @override
  Future<int> saveCustomer(UpsertCustomer customer) async {
    final currentOutletId = await SystemSetting.getCurrentOutletId();

    return await _appDatabase.customerDao.saveCustomer(
      CustomersCompanion(
        localId: Value(customer.id),
        outletId: Value(currentOutletId!),
        name: Value(customer.name),
        email: Value(customer.email),
        phoneNumber: Value(customer.phoneNumber),
        source: Value(CustomerSource.offline.source),
      ),
    );
  }

  @override
  Future<int> deleteCustomer(String id) async {
    return await _appDatabase.customerDao.deleteCustomer(id);
  }
}
