package com.dne.ems.repository.impl;

import com.dne.ems.model.PasswordResetToken;
import com.dne.ems.model.UserAccount;
import com.dne.ems.repository.PasswordResetTokenRepository;
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;

@Repository
@Primary
public class JsonPasswordResetTokenRepositoryImpl implements PasswordResetTokenRepository {

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

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

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

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

    @Override
    public Optional<PasswordResetToken> findByToken(String token) {
        synchronized (cache) {
            return cache.stream().filter(t -> t.getToken().equals(token)).findFirst();
        }
    }

    @Override
    public Optional<PasswordResetToken> findByUser(UserAccount user) {
        synchronized (cache) {
            return cache.stream()
                .filter(t -> t.getUser() != null && t.getUser().equals(user))
                .findFirst();
        }
    }

    @Override
    public void delete(PasswordResetToken token) {
        synchronized (cache) {
            cache.removeIf(t -> t.getId().equals(token.getId()));
            jsonStorageService.writeData(FILE_NAME, cache);
        }
    }
} 