package com.dne.ems.repository.impl;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
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.TaskHistory;
import com.dne.ems.repository.TaskHistoryRepository;
import com.dne.ems.service.JsonStorageService;
import com.fasterxml.jackson.core.type.TypeReference;

import jakarta.annotation.PostConstruct;

@Repository
@Primary
public class JsonTaskHistoryRepositoryImpl implements TaskHistoryRepository {

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

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

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

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

    @Override
    public List<TaskHistory> findByTaskIdOrderByChangedAtDesc(Long taskId) {
        synchronized (cache) {
            return cache.stream()
                .filter(h -> h.getTask() != null && h.getTask().getId().equals(taskId))
                .sorted(Comparator.comparing(TaskHistory::getChangedAt).reversed())
                .collect(Collectors.toList());
        }
    }

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