/// Model de données Budget avec sérialisation JSON
library budget_model;

import 'package:json_annotation/json_annotation.dart';
import '../../domain/entities/budget.dart';

part 'budget_model.g.dart';

@JsonSerializable(explicitToJson: true)
class BudgetModel extends Budget {
  @JsonKey(
    fromJson: _linesFromJson,
    toJson: _linesToJson,
  )
  @override
  final List<BudgetLine> lines;

  const BudgetModel({
    required super.id,
    required super.name,
    super.description,
    required super.organizationId,
    required super.period,
    required super.year,
    super.month,
    required super.status,
    this.lines = const [],
    required super.totalPlanned,
    super.totalRealized,
    super.currency,
    required super.createdBy,
    required super.createdAt,
    super.approvedAt,
    super.approvedBy,
    required super.startDate,
    required super.endDate,
    super.metadata,
  }) : super(lines: lines);

  static List<BudgetLine> _linesFromJson(List<dynamic>? json) =>
      json?.map((e) => BudgetLineModel.fromJson(e as Map<String, dynamic>)).toList() ?? [];

  static List<Map<String, dynamic>> _linesToJson(List<BudgetLine>? lines) =>
      lines?.map((l) => BudgetLineModel(
            id: l.id,
            category: l.category,
            name: l.name,
            description: l.description,
            amountPlanned: l.amountPlanned,
            amountRealized: l.amountRealized,
            notes: l.notes,
          ).toJson()).toList() ?? [];

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

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

  factory BudgetModel.fromEntity(Budget entity) {
    return BudgetModel(
      id: entity.id,
      name: entity.name,
      description: entity.description,
      organizationId: entity.organizationId,
      period: entity.period,
      year: entity.year,
      month: entity.month,
      status: entity.status,
      lines: entity.lines,
      totalPlanned: entity.totalPlanned,
      totalRealized: entity.totalRealized,
      currency: entity.currency,
      createdBy: entity.createdBy,
      createdAt: entity.createdAt,
      approvedAt: entity.approvedAt,
      approvedBy: entity.approvedBy,
      startDate: entity.startDate,
      endDate: entity.endDate,
      metadata: entity.metadata,
    );
  }
}

@JsonSerializable()
class BudgetLineModel extends BudgetLine {
  const BudgetLineModel({
    required super.id,
    required super.category,
    required super.name,
    super.description,
    required super.amountPlanned,
    super.amountRealized,
    super.notes,
  });

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

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