package com.dne.ems.model;

import java.time.LocalDateTime;

import org.hibernate.annotations.CreationTimestamp;

import com.dne.ems.model.enums.OperationType;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 操作日志实体类，用于记录用户的所有操作（不包括查看行为，但包括登录行为）。
 * 每当用户执行重要操作时，会创建一条操作日志记录。
 * 映射到'operation_logs'表。
 *
 * @version 1.0
 * @since 2025-06-20
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
@Table(name = "operation_logs")
public class OperationLog {

    /**
     * 操作日志记录的唯一标识符
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    /**
     * 执行操作的用户
     */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id")
    private UserAccount user;

    /**
     * 操作类型
     */
    @Enumerated(EnumType.STRING)
    @Column(name = "operation_type", nullable = false)
    private OperationType operationType;

    /**
     * 操作描述
     */
    @Column(name = "description", length = 1000)
    private String description;

    /**
     * 操作对象ID（可选）
     */
    @Column(name = "target_id")
    private String targetId;

    /**
     * 操作对象类型（可选）
     */
    @Column(name = "target_type")
    private String targetType;

    /**
     * 客户端IP地址
     */
    @Column(name = "ip_address")
    private String ipAddress;

    /**
     * 操作发生的时间戳，由Hibernate自动管理
     */
    @CreationTimestamp
    @Column(name = "created_at", nullable = false, updatable = false)
    private LocalDateTime createdAt;

    /**
     * 构造一个新的操作日志记录
     *
     * @param user          执行操作的用户
     * @param operationType 操作类型
     * @param description   操作描述
     * @param targetId      操作对象ID
     * @param targetType    操作对象类型
     * @param ipAddress     客户端IP地址
     */
    public OperationLog(UserAccount user, OperationType operationType, String description, 
                        String targetId, String targetType, String ipAddress) {
        this.user = user;
        this.operationType = operationType;
        this.description = description;
        this.targetId = targetId;
        this.targetType = targetType;
        this.ipAddress = ipAddress;
        this.createdAt = LocalDateTime.now();
    }
} 