import 'package:freezed_annotation/freezed_annotation.dart';

part 'license_request_dto.freezed.dart';
part 'license_request_dto.g.dart';

// 날짜를 YYYY-MM-DD 형식으로 변환하는 헬퍼 함수
String? _dateToJson(DateTime? date) {
  if (date == null) return null;
  return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
}

// YYYY-MM-DD 형식 문자열을 DateTime으로 변환하는 헬퍼 함수
DateTime? _dateFromJson(String? dateStr) {
  if (dateStr == null || dateStr.isEmpty) return null;
  try {
    // YYYY-MM-DD 형식 파싱
    if (dateStr.contains('-') && dateStr.length == 10) {
      final parts = dateStr.split('-');
      return DateTime(int.parse(parts[0]), int.parse(parts[1]), int.parse(parts[2]));
    }
    // ISO 8601 형식도 지원
    return DateTime.parse(dateStr);
  } catch (e) {
    return null;
  }
}

/// 라이선스 생성 요청 DTO
@freezed
class CreateLicenseRequest with _$CreateLicenseRequest {
  const factory CreateLicenseRequest({
    @JsonKey(name: 'license_key') required String licenseKey,
    @JsonKey(name: 'product_name') String? productName,
    String? vendor,
    @JsonKey(name: 'license_type') String? licenseType,
    @JsonKey(name: 'user_count') int? userCount,
    @JsonKey(name: 'purchase_date', toJson: _dateToJson, fromJson: _dateFromJson) DateTime? purchaseDate,
    @JsonKey(name: 'expiry_date', toJson: _dateToJson, fromJson: _dateFromJson) DateTime? expiryDate,
    @JsonKey(name: 'purchase_price') double? purchasePrice,
    @JsonKey(name: 'company_id') int? companyId,
    @JsonKey(name: 'branch_id') int? branchId,
    String? remark,
  }) = _CreateLicenseRequest;

  factory CreateLicenseRequest.fromJson(Map<String, dynamic> json) => _$CreateLicenseRequestFromJson(json);
}

/// 라이선스 수정 요청 DTO
@freezed
class UpdateLicenseRequest with _$UpdateLicenseRequest {
  const factory UpdateLicenseRequest({
    @JsonKey(name: 'license_key') String? licenseKey,
    @JsonKey(name: 'product_name') String? productName,
    String? vendor,
    @JsonKey(name: 'license_type') String? licenseType,
    @JsonKey(name: 'user_count') int? userCount,
    @JsonKey(name: 'purchase_date', toJson: _dateToJson, fromJson: _dateFromJson) DateTime? purchaseDate,
    @JsonKey(name: 'expiry_date', toJson: _dateToJson, fromJson: _dateFromJson) DateTime? expiryDate,
    @JsonKey(name: 'purchase_price') double? purchasePrice,
    String? remark,
    @JsonKey(name: 'is_active') bool? isActive,
  }) = _UpdateLicenseRequest;

  factory UpdateLicenseRequest.fromJson(Map<String, dynamic> json) => _$UpdateLicenseRequestFromJson(json);
}

/// 라이선스 사용자 할당 요청 DTO
@freezed
class AssignLicenseRequest with _$AssignLicenseRequest {
  const factory AssignLicenseRequest({
    @JsonKey(name: 'user_id') required int userId,
  }) = _AssignLicenseRequest;

  factory AssignLicenseRequest.fromJson(Map<String, dynamic> json) => _$AssignLicenseRequestFromJson(json);
}