package com.iqser.red.persistence.service.v1.external.api.impl.controller;

import static com.iqser.red.service.persistence.management.v1.processor.roles.ActionRoles.READ_USER_STATS;

import java.util.ArrayList;
import java.util.List;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RestController;

import com.iqser.red.service.persistence.management.v1.processor.acl.custom.dossier.DossierACLService;
import com.iqser.red.service.persistence.management.v1.processor.exception.NotFoundException;
import com.iqser.red.service.persistence.management.v1.processor.service.DossierService;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.FileStatusPersistenceService;
import com.iqser.red.service.persistence.management.v1.processor.service.users.UserService;
import com.iqser.red.service.persistence.service.v1.api.external.resource.UserStatsResource;
import com.iqser.red.service.persistence.service.v1.api.shared.model.UserStats;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequiredArgsConstructor
public class UserStatsController implements UserStatsResource {

    private final UserService userService;
    private final DossierService dossierService;
    private final FileStatusPersistenceService fileStatusPersistenceService;
    private final DossierACLService dossierACLService;


    @Override
    @PreAuthorize("hasAuthority('" + READ_USER_STATS + "')")
    public ResponseEntity<UserStats> getUserStats(String userId) {

        if (userService.getUserById(userId).isEmpty()) {
            throw new NotFoundException(String.format("The user with id %s is not found.", userId));
        }
        List<String> dossierMemberships = new ArrayList<>();
        List<String> dossierOwnerships = new ArrayList<>();
        dossierService.getAllDossiers()
                .stream()
                .filter(dossierEntity -> dossierEntity.getHardDeletedTime() == null)
                .forEach(d -> {
                    if (dossierACLService.getMembers(d.getId()).contains(userId)) {
                        dossierMemberships.add(d.getId());
                    }
                    if (dossierACLService.getOwners(d.getId()).contains(userId)) {
                        dossierOwnerships.add(d.getId());
                    }
                });

        return new ResponseEntity<>(new UserStats(dossierMemberships.size(), dossierOwnerships.size(), this.fileStatusPersistenceService.getNumberOfAssignedFiles(userId)),
                                    HttpStatus.OK);
    }

}