package com.dne.ems.repository.impl;

import com.dne.ems.model.Attachment;
import com.dne.ems.model.Feedback;
import com.dne.ems.model.TaskSubmission;
import com.dne.ems.repository.AttachmentRepository;
import com.dne.ems.service.JsonStorageService;
import com.fasterxml.jackson.core.type.TypeReference;
import jakarta.annotation.PostConstruct;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

@Repository
@Primary
public class JsonAttachmentRepositoryImpl implements AttachmentRepository {

    private static final String FILE_NAME = "attachments.json";
    private final JsonStorageService jsonStorageService;
    private final List<Attachment> cache = new ArrayList<>();
    private final AtomicLong idCounter = new AtomicLong(0);

    public JsonAttachmentRepositoryImpl(JsonStorageService jsonStorageService) {
        this.jsonStorageService = jsonStorageService;
    }

    @PostConstruct
    public void init() {
        List<Attachment> data = jsonStorageService.readData(FILE_NAME, new TypeReference<>() {});
        synchronized (cache) {
            cache.addAll(data);
            long maxId = data.stream()
                              .mapToLong(Attachment::getId)
                              .max()
                              .orElse(0L);
            idCounter.set(maxId);
        }
    }

    @Override
    public Attachment save(Attachment attachment) {
        synchronized (cache) {
            if (attachment.getId() == null) {
                attachment.setId(idCounter.incrementAndGet());
                cache.add(attachment);
            } else {
                cache.removeIf(a -> a.getId().equals(attachment.getId()));
                cache.add(attachment);
            }
            jsonStorageService.writeData(FILE_NAME, cache);
            return attachment;
        }
    }

    @Override
    public Optional<Attachment> findByStoredFileName(String storedFileName) {
        synchronized (cache) {
            return cache.stream().filter(a -> a.getStoredFileName().equals(storedFileName)).findFirst();
        }
    }

    @Override
    public List<Attachment> findByTaskSubmission(TaskSubmission taskSubmission) {
        synchronized (cache) {
            return cache.stream()
                .filter(a -> a.getTaskSubmission() != null && a.getTaskSubmission().equals(taskSubmission))
                .collect(Collectors.toList());
        }
    }

    @Override
    public List<Attachment> findByFeedback(Feedback feedback) {
        synchronized (cache) {
            return cache.stream()
                .filter(a -> a.getFeedback() != null && a.getFeedback().equals(feedback))
                .collect(Collectors.toList());
        }
    }
} 