package com.caliverse.admin.mongodb.domain;

import com.caliverse.admin.domain.entity.FieldChange;
import com.caliverse.admin.domain.entity.HISTORYTYPEDETAIL;
import com.caliverse.admin.mongodb.entity.DBType;
import com.caliverse.admin.mongodb.entity.EDBOperationType;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Field;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;

@Getter
@Setter
@NoArgsConstructor
public class HistoryLogInfoBase implements historyLog {

    @Id
    private String id;
    private DBType dbType;
    private String timestamp;
    private EDBOperationType operationType;
    private HISTORYTYPEDETAIL historyType;
    private String tableName;
    private String message;
    private String tranId;
    private List<FieldChange> changed;
    private String userId;
    private String userIP;

    public LocalDateTime getTimestampAsLocalDateTime() {
        if (timestamp == null || timestamp.isEmpty()) {
            return null;
        }

        try {
            // 기본 형식 시도
            return LocalDateTime.parse(timestamp, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        } catch (DateTimeParseException e1) {
            try {
                // ISO 형식 시도
                return LocalDateTime.parse(timestamp, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"));
            } catch (DateTimeParseException e2) {
                throw new IllegalArgumentException("Unable to parse timestamp: " + timestamp);
            }
        }
    }

    public HistoryLogInfoBase(DBType dbType,
                              LocalDateTime timestamp,
                              EDBOperationType operationType,
                              HISTORYTYPEDETAIL historyType,
                              String tableName,
                              String message,
                              String tranId,
                              List<FieldChange> changed,
                              String userId,
                              String userIP
    ) {
        this.dbType = dbType;
        this.timestamp = timestamp != null ? timestamp.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) : null;
        this.operationType = operationType;
        this.historyType = historyType;
        this.tableName = tableName;
        this.message = message;
        this.tranId = tranId;
        this.changed = changed;
        this.userId = userId;
        this.userIP = userIP;
    }
}
