package ai.decompile.workspace.service;

import ai.decompile.common.exception.ConflictException;
import ai.decompile.common.exception.NotFoundException;
import ai.decompile.workspace.model.dto.WorkspaceRequest;
import ai.decompile.workspace.model.dto.WorkspaceResponse;
import ai.decompile.workspace.model.entity.Workspace;
import ai.decompile.workspace.model.repository.WorkspaceRepository;
import ai.decompile.workspace.model.specification.WorkspaceSpecification;
import java.util.List;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class WorkspaceService {
  private final WorkspaceRepository workspaceRepository;

  public List<WorkspaceResponse> getWorkspaces(String name) {
    List<Workspace> workspaces;
    if (StringUtils.isNotBlank(name)) {
      workspaces = workspaceRepository.findAll(WorkspaceSpecification.nameContains(name));
    } else {
      workspaces = workspaceRepository.findAll();
    }

    return workspaces.stream().map(WorkspaceResponse::from).toList();
  }

  public WorkspaceResponse getWorkspaceById(UUID id) {
    return WorkspaceResponse.from(getWorkspace(id));
  }

  public WorkspaceResponse createWorkspace(WorkspaceRequest request) {
    if (workspaceRepository.existsByNameIgnoreCase(request.name())) {
      throw new ConflictException(
          "A workspace with the name '" + request.name() + "' already exists.");
    }

    var workspace =
        workspaceRepository.save(
            Workspace.builder().name(request.name()).description(request.description()).build());

    return WorkspaceResponse.from(workspace);
  }

  public WorkspaceResponse updateWorkspace(UUID id, WorkspaceRequest request) {
    var workspace = getWorkspace(id);

    workspace.setName(request.name());
    workspace.setDescription(request.description());

    return WorkspaceResponse.from(workspaceRepository.save(workspace));
  }

  public void deleteWorkspace(UUID id) {
    var workspace = getWorkspace(id);
    workspaceRepository.delete(workspace);
  }

  protected Workspace getWorkspace(UUID id) {
    return workspaceRepository
        .findById(id)
        .orElseThrow(() -> new NotFoundException("Workspace with id '" + id + "' not found"));
  }
}
