part of '../printer_dtos.dart';

@freezed
class PrinterDto with _$PrinterDto {
  const PrinterDto._();

  const factory PrinterDto({
    @JsonKey(name: 'id') required int id,
    @JsonKey(name: 'code') required String code,
    @JsonKey(name: 'name') required String name,
    @JsonKey(name: 'address') required String address,
    @JsonKey(name: 'paper') required String paper,
    @JsonKey(name: 'type') required String type,
    @JsonKey(name: 'created_at') required DateTime createdAt,
    @JsonKey(name: 'updated_at') required DateTime updatedAt,
  }) = _PrinterDto;

  factory PrinterDto.fromJson(Map<String, dynamic> json) => _$PrinterDtoFromJson(
    // Normalize paper field: SQLite bisa return int atau String
    {
      ...json,
      'paper': json['paper']?.toString() ?? '58',
      'created_at': json['created_at'] is DateTime
          ? (json['created_at'] as DateTime).toIso8601String()
          : json['created_at'],
      'updated_at': json['updated_at'] is DateTime
          ? (json['updated_at'] as DateTime).toIso8601String()
          : json['updated_at'],
    },
  );

  // Optional mapper to domain
  Printer toDomain() => Printer(
    id: id,
    code: code,
    name: name,
    address: address,
    paper: paper,
    type: type,
    createdAt: createdAt,
    updatedAt: updatedAt,
  );

  factory PrinterDto.fromDomain(Printer printer) => PrinterDto(
    id: printer.id,
    code: printer.code,
    name: printer.name,
    address: printer.address,
    paper: printer.paper,
    type: printer.type,
    createdAt: printer.createdAt,
    updatedAt: printer.updatedAt,
  );

  Map<String, dynamic> toMapCreating() {
    final now = DateTime.now().toIso8601String();
    return {
      'id': generateRandomNumber(),
      'code': code,
      'name': name,
      'address': address,
      'paper': paper,
      'type': type,
      'created_at': now,
      'updated_at': now,
    };
  }

  Map<String, dynamic> toMapForUpdate() {
    return {
      'code': code,
      'name': name,
      'address': address,
      'paper': paper,
      'type': type,
      'updated_at': DateTime.now().toIso8601String(),
    };
  }
}
