import 'package:pocketbase/pocketbase.dart';
import '../../core/api/pocketbase_client.dart';
import '../../models/tenant.dart';
import '../../models/user_profile.dart';

class TeamMember {
  const TeamMember({
    required this.memberId,
    required this.user,
    required this.role,
    required this.joinedAt,
  });
  final String memberId;
  final UserProfile user;
  final TenantRole role;
  final DateTime joinedAt;
}

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

  PocketBase get _pb => PocketBaseClient.instance.pb;

  Future<List<TeamMember>> listMembers(String tenantId) async {
    final result = await _pb.collection('tenant_members').getList(
      filter: 'tenant_id = "$tenantId"',
      expand: 'user_id',
      perPage: 200,
    );
    return (result.items.map((r) {
      final j = r.toJson();
      final userExp = (j['expand'] as Map?)?['user_id'] as Map<String, dynamic>?;
      return TeamMember(
        memberId: j['id'] as String,
        user: UserProfile.fromJson(userExp ?? {'id': j['user_id'], 'email': ''}),
        role: TenantMembership.parseRole(j['role'] as String),
        joinedAt: DateTime.parse(j['created'] as String),
      );
    }).toList()..sort((a, b) => a.joinedAt.compareTo(b.joinedAt)));
  }

  Future<TeamMember> addMember({
    required String tenantId,
    required String email,
    required String password,
    required String firstName,
    required String lastName,
    required TenantRole role,
  }) async {
    final userRecord = await _pb.collection('users').create(body: {
      'email': email.trim().toLowerCase(),
      'password': password,
      'passwordConfirm': password,
      'first_name': firstName.trim(),
      'last_name': lastName.trim(),
      'emailVisibility': true,
    });
    final memberRecord = await _pb.collection('tenant_members').create(body: {
      'tenant_id': tenantId,
      'user_id': userRecord.id,
      'role': role.value,
    });
    final j = memberRecord.toJson();
    return TeamMember(
      memberId: j['id'] as String,
      user: UserProfile.fromJson(userRecord.toJson()),
      role: role,
      joinedAt: DateTime.parse(j['created'] as String),
    );
  }

  Future<void> changeMemberRole(String memberId, TenantRole newRole) async {
    await _pb.collection('tenant_members').update(memberId, body: {
      'role': newRole.value,
    });
  }

  Future<void> removeMember(String memberId) async {
    await _pb.collection('tenant_members').delete(memberId);
  }
}
