package com.dne.ems.repository.impl;

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

import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Repository;

import com.dne.ems.model.Task;
import com.dne.ems.model.TaskSubmission;
import com.dne.ems.repository.TaskSubmissionRepository;
import com.dne.ems.service.JsonStorageService;
import com.fasterxml.jackson.core.type.TypeReference;

import jakarta.annotation.PostConstruct;

@Repository
@Primary
public class JsonTaskSubmissionRepositoryImpl implements TaskSubmissionRepository {

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

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

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

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

    @Override
    public TaskSubmission findFirstByTaskOrderBySubmittedAtDesc(Task task) {
        synchronized (cache) {
            return cache.stream()
                .filter(s -> s.getTask() != null && s.getTask().equals(task))
                .max(Comparator.comparing(TaskSubmission::getSubmittedAt))
                .orElse(null);
        }
    }

    @Override
    public List<TaskSubmission> findByTaskId(Long taskId) {
        synchronized (cache) {
            return cache.stream()
                .filter(s -> s.getTask() != null && Objects.equals(s.getTask().getId(), taskId))
                .collect(Collectors.toList());
        }
    }

    @Override
    public List<TaskSubmission> findAll() {
        synchronized (cache) {
            return new ArrayList<>(cache);
        }
    }

    @Override
    public void deleteAll() {
        synchronized (cache) {
            cache.clear();
            jsonStorageService.writeData(FILE_NAME, cache);
        }
    }
} 