package com.dne.ems.repository.impl;

import com.dne.ems.model.AssignmentRecord;
import com.dne.ems.repository.AssignmentRecordRepository;
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;
import java.util.stream.StreamSupport;

@Repository
@Primary
public class JsonAssignmentRecordRepositoryImpl implements AssignmentRecordRepository {

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

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

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

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

    @Override
    public List<AssignmentRecord> saveAll(Iterable<AssignmentRecord> records) {
        synchronized (cache) {
            List<AssignmentRecord> savedRecords = StreamSupport.stream(records.spliterator(), false)
                .map(this::save)
                .collect(Collectors.toList());
            return savedRecords;
        }
    }

    @Override
    public Optional<AssignmentRecord> findById(Long id) {
        synchronized (cache) {
            return cache.stream().filter(r -> r.getId().equals(id)).findFirst();
        }
    }

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

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