package com.dne.ems.repository.impl;

import com.dne.ems.model.Assignment;
import com.dne.ems.repository.AssignmentRepository;
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.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

@Repository
@Primary
public class JsonAssignmentRepositoryImpl implements AssignmentRepository {

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

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

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

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

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

    @Override
    public List<Assignment> findByTaskAssigneeId(Long assigneeId) {
        synchronized (cache) {
            return cache.stream()
                .filter(a -> a.getTask() != null && a.getTask().getAssignee() != null && a.getTask().getAssignee().getId().equals(assigneeId))
                .collect(Collectors.toList());
        }
    }
} 