import 'dart:convert';
import 'package:json_annotation/json_annotation.dart';
import 'package:mypoint_flutter_app/features/register_campaign/model/registration_form_package_verify_model.dart';
import 'input_form_registration_model.dart';

part 'registration_form_package_model.g.dart';
@JsonSerializable()
class RegistrationFormPackageModel {
  @JsonKey(name: 'product_id')
  final String? productId;
  final VerifyModel? verify;
  @JsonKey(name: 'is_checked_registration')
  final bool? isCheckedRegistration;
  final String? id;
  final String? title;
  @JsonKey(name: 'form_confirm')
  final InputFormRegistrationModel? formConfirm;
  @JsonKey(name: 'click_action_param')
  final String? clickActionParam;
  @JsonKey(name: 'click_action_type')
  final String? clickActionType;
  @JsonKey(name: 'form_registration')
  final InputFormRegistrationModel? formRegistration;

  RegistrationFormPackageModel({
    this.productId,
    this.verify,
    this.isCheckedRegistration,
    this.id,
    this.title,
    this.formConfirm,
    this.clickActionParam,
    this.clickActionType,
    this.formRegistration,
  });

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

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

  Map<String, dynamic> get submitParams {
    final inputs = formRegistration?.inputRequired;
    if (inputs == null || inputs.isEmpty) return {};
    final out = <String, dynamic>{};
    for (final item in inputs) {
      // Ưu tiên code_default, nếu rỗng fallback content
      final value = [item.codeDefault, item.content, item.defaultValue]
          .firstWhere((s) => s?.trim().isNotEmpty ?? false, orElse: () => item.defaultValue);
      out[item.key ?? ''] = value;
    }
    return {'form_card': out};
  }
}

extension JsonStringX on Map<String, dynamic> {
  /// Convert Map -> JSON String
  /// - [prettify]: thêm indent 2 spaces cho dễ đọc
  String? toJsonString({bool prettify = false}) {
    try {
      final encoder = prettify
          ? const JsonEncoder.withIndent('  ')
          : const JsonEncoder();
      return encoder.convert(this);
    } catch (_) {
      return null; // Không encode được (có thể do giá trị không JSON-encodable)
    }
  }
}