package ru.soune.nocopy.entity.file;

import jakarta.persistence.*;
import lombok.*;
import org.springframework.data.annotation.CreatedDate;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "file_upload_sessions")
public class FileUploadSession {

    @Id
    @GeneratedValue(strategy = GenerationType.UUID)
    @Column(name = "upload_id")
    private String uploadId;

    @Column(name = "user_id", nullable = false)
    private Long userId;

    @Column(name = "file_name", nullable = false)
    private String fileName;

    @Column(name = "file_type")
    private String fileType;

    @Column(name = "file_size")
    private Long fileSize;

    @Column(name = "chunk_size")
    private Long chunkSize;

    @Column(name = "total_chunks")
    private Integer totalChunks;

    @Column(name = "chunks_uploaded")
    private Integer chunksUploaded;

    @Column(name = "status")
    @Enumerated(EnumType.STRING)
    private UploadStatus status;

    @Column(name = "file_path")
    private String filePath;

    @Column(name = "checksum")
    private String checksum;

    @CreatedDate
    @Column(name = "created_at", updatable = false, nullable = false)
    private LocalDateTime createdAt;

    @Column(name = "expires_at")
    private LocalDateTime expiresAt;

    @Version
    private Long version;

    @Column(name = "last_error")
    private String lastError;

    @Column(name = "extension")
    private String extension;

    @Column(name = "retry_count")
    @Builder.Default
    private Integer retryCount = 0;

    @Column(name = "completed_at")
    private LocalDateTime completedAt;

    @Column(name = "convert_to")
    String convertTo;

    @ElementCollection
    @CollectionTable(
            name = "uploaded_chunks",
            joinColumns = @JoinColumn(name = "upload_id")
    )
    @MapKeyColumn(name = "chunk_number")
    @Column(name = "chunk_path")
    @Builder.Default
    private Map<Integer, String> chunkPaths = new HashMap<>();

    @PrePersist
    public void prePersist() {
        this.createdAt = LocalDateTime.now();
        this.expiresAt = LocalDateTime.now().plusMinutes(1);
        if (this.chunksUploaded == null) {
            this.chunksUploaded = 0;
        }
        if (this.status == null) {
            this.status = UploadStatus.INITIATED;
        }
        if (this.retryCount == null) {
            this.retryCount = 0;
        }
    }
}