import 'package:drift/drift.dart' hide JsonKey;
import 'package:json_annotation/json_annotation.dart';
import 'package:niogu_app/core/database/app_database.dart';
import 'package:niogu_app/core/models/outlet_model.dart';
import 'package:niogu_app/core/models/staff_model.dart';
import 'package:niogu_app/core/models/tenant_model.dart';
import 'package:niogu_app/core/enums/sync_status.dart';

part 'user_model.g.dart';

@JsonSerializable()
class UserModel {
  @JsonKey(name: 'id')
  final String serverId;

  final TenantModel tenant;

  @JsonKey(name: 'outlet_id')
  final String outletId;

  @JsonKey(name: 'outlets')
  final dynamic rawOutlets;

  @JsonKey(name: 'staff_list', defaultValue: [])
  final List<StaffModel> staffs;

  final String name;

  final String? email;

  @JsonKey(name: 'phone_number')
  final String? phoneNumber;

  final String role;

  @JsonKey(name: 'place_of_birth')
  final String? placeOfBirth;

  @JsonKey(name: 'date_of_birth')
  final String? dateOfBirth;

  @JsonKey(name: 'shift_name')
  final String? shiftName;

  @JsonKey(name: 'shift_start_time')
  final String? shiftStartTime;

  @JsonKey(name: 'shift_end_time')
  final String? shiftEndTime;

  @JsonKey(name: 'is_active')
  final bool isActive;

  @JsonKey(name: 'created_at')
  final DateTime createdAt;

  @JsonKey(name: 'updated_at')
  final DateTime updatedAt;

  const UserModel({
    required this.serverId,
    required this.tenant,
    required this.outletId,
    required this.rawOutlets,
    required this.staffs,
    required this.name,
    this.email,
    this.phoneNumber,
    required this.role,
    this.placeOfBirth,
    this.dateOfBirth,
    this.shiftName,
    this.shiftStartTime,
    this.shiftEndTime,
    required this.isActive,
    required this.createdAt,
    required this.updatedAt,
  });

  List<OutletModel> get outlets {
    if (rawOutlets is List) {
      return (rawOutlets as List)
          .map((e) => OutletModel.fromJson(e as Map<String, dynamic>))
          .toList();
    }
    // Jika berupa single object (Staff)
    return [OutletModel.fromJson(rawOutlets as Map<String, dynamic>)];
  }

  factory UserModel.fromJson(Map<String, dynamic> json) =>
      _$UserModelFromJson(json);

  Map<String, dynamic> toJson() => _$UserModelToJson(this);

  UsersCompanion toDriftCompanion(String password) {
    return UsersCompanion(
      localId: Value(serverId),
      serverId: Value(serverId),
      outletId: Value(outletId),
      name: Value(name),
      email: Value(email),
      phoneNumber: Value(phoneNumber),
      passwordHash: Value(password),
      role: Value(role),
      placeOfBirth: Value(placeOfBirth),
      dateOfBirth: Value(dateOfBirth),
      shiftName: Value(shiftName),
      shiftStartTime: Value(shiftStartTime),
      shiftEndTime: Value(shiftEndTime),
      isActive: Value(isActive),
      syncStatus: Value(SyncStatus.synced.status),
      createdAt: Value(createdAt),
      updatedAt: Value(updatedAt),
    );
  }
}
