import 'dart:io';

class CookieEntry {
  final String value;
  final DateTime? expires;
  final String? path;
  final String? domain;

  CookieEntry({
    required this.value,
    this.expires,
    this.path,
    this.domain,
  });

  factory CookieEntry.fromSetCookie(String raw) {
    final parts = raw.split(';');
    final kv = parts[0].split('=');
    final name = kv[0].trim();
    final value = kv.length > 1 ? kv.sublist(1).join('=').trim() : '';

    String? path;
    String? domain;
    DateTime? expires;

    for (final part in parts.skip(1)) {
      final kv = part.trim().split('=');
      final key = kv[0].toLowerCase();
      final val = kv.length > 1 ? kv.sublist(1).join('=').trim() : '';
      switch (key) {
        case 'expires':
          try {
            expires = HttpDate.parse(val);
          } catch (_) {}
          break;
        case 'path':
          path = val;
          break;
        case 'domain':
          domain = val;
          break;
      }
    }

    return CookieEntry(
      value: value,
      expires: expires,
      path: path,
      domain: domain,
    );
  }

  Map<String, dynamic> toJson() => {
    'value': value,
    'expires': expires?.toIso8601String(),
    'path': path,
    'domain': domain,
  };

  static CookieEntry fromJson(Map<String, dynamic> json) => CookieEntry(
    value: json['value'],
    expires: json['expires'] != null ? DateTime.parse(json['expires']) : null,
    path: json['path'],
    domain: json['domain'],
  );

  String toCookieString(String name) => '$name=$value';
}
