package dev.dinauer.maven.app;

import dev.dinauer.maven.event.Event;
import dev.dinauer.maven.event.EventType;
import dev.dinauer.maven.event.Resource;
import dev.dinauer.maven.event.repo.EventRepo;
import dev.dinauer.maven.maven.core.GroupRepo;
import dev.dinauer.maven.maven.core.GroupId;
import io.quarkus.security.identity.SecurityIdentity;
import jakarta.inject.Inject;
import jakarta.transaction.Transactional;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;

import java.time.ZonedDateTime;
import java.util.List;

@Path("/groups")
public class GroupResource
{
    @Inject
    GroupRepo groupRepo;

    @Inject
    EventRepo eventRepo;

    @Inject
    SecurityIdentity securityIdentity;

    @Inject
    GroupMapper groupMapper;

    @GET
    public List<GroupDTO> get()
    {
        return groupMapper.map(groupRepo.listAll());
    }

    @GET
    @Path("/{id}")
    public GroupId get(@PathParam("id") String id)
    {
        return groupRepo.findById(id);
    }

    @DELETE
    @Path("/{id}")
    @Transactional
    public void delete(@PathParam("id") String id)
    {
        GroupId groupId = groupRepo.findById(id);
        if (groupId != null)
        {
            groupRepo.delete(groupId);
            eventRepo.persist(new Event().setUserId(securityIdentity.getPrincipal().getName()).setType(EventType.DELETE).setTimestamp(ZonedDateTime.now()).setResource(new Resource().setGroupId(groupId.getGroupId())));
        }
    }
}
