import 'package:cloud_firestore/cloud_firestore.dart';

class Schedule {
  final String id;
  final String petId;
  final DateTime date;
  final String type; // 'general', 'important'
  final bool isCompleted;
  final String title;
  final String? note;
  final DateTime createdAt;
  final int? repeatInterval; // 반복 간격 (1, 2, ...)
  final String? repeatUnit; // 반복 단위 ('day', 'week', 'month', 'year')
  final bool isAlarmOn; // 알림 설정 여부
  final DateTime? alarmTime; // 알림 시간

  Schedule({
    required this.id,
    required this.petId,
    required this.date,
    required this.type,
    required this.isCompleted,
    required this.title,
    this.note,
    required this.createdAt,
    this.repeatInterval,
    this.repeatUnit,
    this.isAlarmOn = false,
    this.alarmTime,
  });

  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'petId': petId,
      'date': Timestamp.fromDate(date),
      'type': type,
      'isCompleted': isCompleted,
      'title': title,
      'note': note,
      'createdAt': Timestamp.fromDate(createdAt),
      'repeatInterval': repeatInterval,
      'repeatUnit': repeatUnit,
      'isAlarmOn': isAlarmOn,
      'alarmTime': alarmTime != null ? Timestamp.fromDate(alarmTime!) : null,
    };
  }

  factory Schedule.fromMap(Map<String, dynamic> map) {
    DateTime parseDate(dynamic value) {
      if (value is Timestamp) return value.toDate();
      if (value is String) return DateTime.tryParse(value) ?? DateTime.now();
      return DateTime.now();
    }

    return Schedule(
      id: map['id']?.toString() ?? '',
      petId: map['petId']?.toString() ?? '',
      date: parseDate(map['date']),
      type: map['type']?.toString() ?? 'general',
      isCompleted: map['isCompleted'] == true,
      title: map['title']?.toString() ?? '',
      note: map['note']?.toString(),
      createdAt: parseDate(map['createdAt']),
      repeatInterval: map['repeatInterval'] as int?,
      repeatUnit: map['repeatUnit']?.toString(),
      isAlarmOn: map['isAlarmOn'] == true,
      alarmTime: map['alarmTime'] != null ? parseDate(map['alarmTime']) : null,
    );
  }
}
