package com.vaessl.app.sync;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.vaessl.app.shared.SessionKeys;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;

@RestController
public class SyncController {

    private final SyncService syncService;

    public SyncController(SyncService syncService) {
        this.syncService = syncService;
    }

    /**
     * Triggers a vector-store sync for the requested service. Returns {@code 401 Unauthorized}
     * if there is no active session.
     */
    @PostMapping("/sync")
    public ResponseEntity<Object> syncVectorStore(@Valid @RequestBody SyncRequest request,
            HttpServletRequest httpReq) {

        HttpSession session = httpReq.getSession(false);

        if (session == null
                || session.getAttribute(SessionKeys.connectionId(request.serviceType())) == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        syncService.syncServiceVectorStore(request);

        return ResponseEntity.noContent().build();
    }
}
