/**
 * Copyright (c) 2025 SoftCorporation LLC. All rights reserved.
 *
 * The Software License, Version 1.0
 *
 * SoftCorporation LLC. grants you ("Licensee") a non-exclusive, royalty free,
 * license to use, modify and redistribute this software in source and binary
 * code form, provided that the following conditions are met:
 *
 * 1. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        SoftCorporation LLC. (http://www.softcorporation.com)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 2. This software and SoftCorporation name must not be used to
 *    promote products derived from the software without prior
 *    written permission. For written permission, please contact
 *    info@softcorporation.com.
 *
 * This software is provided "AS IS," without a warranty of any kind.
 * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
 * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED.
 * IN NO EVENT SHALL THE SOFTCORPORATION BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION).
 *
 */
package com.softcorporation.sandi.index.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import com.softcorporation.sandi.base.model.Client;
import com.softcorporation.sandi.base.service.ClientService;
import com.softcorporation.sandi.base.util.Constants;
import com.softcorporation.sandi.index.model.DeleteRequest;
import com.softcorporation.sandi.index.model.DeleteResponse;
import com.softcorporation.sandi.index.service.IndexerService;
import com.softcorporation.sandi.index.util.IndexerException;

@RestController
@RequestMapping("/delete")
public class DeleteController {

    private static final Logger LOGGER = LoggerFactory.getLogger(DeleteController.class);

    @Autowired
    private ClientService clientService;

    @Autowired
    private IndexerService indexerService;

    @PostMapping
    public ResponseEntity<DeleteResponse> deleteDocuments(@RequestBody DeleteRequest request) {
        
        final String requestId = request.getRequestId();
        final String clientId = request.getClientId();
        
        LOGGER.debug("[{}] Received delete request: clientId={}", requestId, clientId);
        
        // Validate request
        DeleteResponse validationError = validateRequest(request);
        if (validationError != null) {
            return ResponseEntity.badRequest().body(validationError);
        }
        
        try {
            Client client = clientService.getClient(clientId);
            if (client == null) {
                LOGGER.warn("[{}] Client not found: {}", requestId, clientId);
                DeleteResponse response = new DeleteResponse(requestId, Constants.STATUS_ERROR, "Client not found");
                return ResponseEntity.badRequest().body(response);
            }

            if (!client.isActive()) {
                LOGGER.warn("[{}] Client is inactive: {}", requestId, clientId);
                DeleteResponse response = new DeleteResponse(requestId, Constants.STATUS_ERROR, "Client is inactive");
                return ResponseEntity.badRequest().body(response);
            }

            boolean deleted = false;
            if (request.getId() != null && !request.getId().isEmpty()) {
                indexerService.deleteDocument(client.getCollection(), client.getClientId(), request.getId());
                deleted = true;
            }
            if (request.getIds() != null && !request.getIds().isEmpty()) {
                indexerService.deleteDocuments(client.getCollection(), client.getClientId(), request.getIds());
                deleted = true;
            }
            if (request.getQuery() != null && !request.getQuery().isEmpty()) {
                indexerService.deleteDocumentsByQuery(client.getCollection(), client.getClientId(), request.getQuery());
                deleted = true;
            }

            DeleteResponse response;
            if (deleted) {
                response = new DeleteResponse(requestId, Constants.STATUS_SUCCESS, "Delete completed successfully");
                LOGGER.info("[{}] Delete successful: clientId={}, collection={}", 
                           requestId, clientId, client.getCollection());
            } else {
                LOGGER.warn("[{}] Nothing to delete for clientId={}, collection={}", 
                           requestId, clientId, client.getCollection());
                throw new IndexerException("Nothing to delete");
            }
            response.setDeleted(0);
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            LOGGER.error("[{}] Delete failed: {}", requestId, e.getMessage(), e);
            DeleteResponse response = new DeleteResponse(requestId, Constants.STATUS_ERROR, "Delete failed: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * Validates delete request
     * @param request the request to validate
     * @return DeleteResponse with error if validation fails, null if valid
     */
    private DeleteResponse validateRequest(DeleteRequest request) {
        if (request.getRequestId() == null || request.getRequestId().trim().isEmpty()) {
            LOGGER.warn("JSON index request missing requestId");
            return new DeleteResponse(Constants.MISSING, Constants.STATUS_ERROR, "RequestId is required");
        }
        
        if (request.getClientId() == null || request.getClientId().trim().isEmpty()) {
            LOGGER.warn("JSON index request missing clientId");
            return new DeleteResponse(request.getRequestId(), Constants.STATUS_ERROR, "ClientId is required");
        }
        return null;
    }

}