import 'package:pocketbase/pocketbase.dart';
import '../../core/api/pocketbase_client.dart';
import '../../core/auth/auth_repository.dart';

class OnboardingRepository {
  OnboardingRepository._();
  static final instance = OnboardingRepository._();

  PocketBase get _pb => PocketBaseClient.instance.pb;

  Future<AuthResult> createTenantAndJoin({
    required String kind,
    required String companyName,
    String? companyAddress,
    String? city,
    String? district,
    double? latitude,
    double? longitude,
  }) async {
    final userId = _pb.authStore.record!.id;

    final tenant = await _pb.collection('tenants').create(body: {
      'kind': kind,
      'company_name': companyName,
      'company_address': companyAddress,
      'city': city,
      'district': district,
      'latitude': latitude,
      'longitude': longitude,
      'status': 'active',
      'default_currency': 'TRY',
    });

    await _pb.collection('tenant_members').create(body: {
      'tenant_id': tenant.id,
      'user_id': userId,
      'role': 'owner',
    });

    return AuthRepository.instance.refreshSession();
  }
}
