/// Kapcsolat (névjegy) — a Supabase `contacts` táblát tükrözi.
///
/// Ez a menü CSAK online, bejelentkezett és jogosult felhasználóknak
/// érhető el, ezért nincs lokális tükrözés/offline-sync: közvetlenül a
/// Supabase-ből olvassuk/írjuk, a hozzáférést az RLS + a jogosultság-
/// tábla dönti el. Az uuid szerveroldali (gen_random_uuid()).
class Contact {
  final String? id; // uuid — új rekordnál null, a szerver adja
  final String
      projectId; // az AKTUÁLIS projekt uuid-ja (terepi_seged_projects.id)
  final String name;
  final String address;
  final String phone;
  final String email;
  final String note;
  final String? createdBy;
  final DateTime? updatedAt;

  const Contact({
    this.id,
    required this.projectId,
    required this.name,
    this.address = '',
    this.phone = '',
    this.email = '',
    this.note = '',
    this.createdBy,
    this.updatedAt,
  });

  Contact copyWith({
    String? name,
    String? address,
    String? phone,
    String? email,
    String? note,
  }) =>
      Contact(
        id: id,
        projectId: projectId,
        name: name ?? this.name,
        address: address ?? this.address,
        phone: phone ?? this.phone,
        email: email ?? this.email,
        note: note ?? this.note,
        createdBy: createdBy,
        updatedAt: updatedAt,
      );

  /// Beszúráshoz/frissítéshez — az id-t csak akkor küldjük, ha van
  /// (frissítésnél), a szerveroldali mezőket (created_by, updated_at)
  /// sosem a kliens állítja.
  Map<String, dynamic> toWriteMap() => {
        if (id != null) 'id': id,
        'project_id': projectId,
        'name': name.trim(),
        'address': address.trim(),
        'phone': phone.trim(),
        'email': email.trim(),
        'note': note.trim(),
      };

  factory Contact.fromMap(Map<String, dynamic> m) => Contact(
        id: m['id'] as String?,
        projectId: m['project_id'] as String,
        name: (m['name'] as String?) ?? '',
        address: (m['address'] as String?) ?? '',
        phone: (m['phone'] as String?) ?? '',
        email: (m['email'] as String?) ?? '',
        note: (m['note'] as String?) ?? '',
        createdBy: m['created_by'] as String?,
        updatedAt: m['updated_at'] != null
            ? DateTime.tryParse(m['updated_at'] as String)
            : null,
      );
}
