/**
 * 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 java.util.List;
import java.util.Map;

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.IndexResponse;
import com.softcorporation.sandi.index.model.IndexRequest;
import com.softcorporation.sandi.index.service.IndexerService;

@RestController
@RequestMapping("/index")
public class IndexController {

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

    @Autowired
    private ClientService clientService;

    @Autowired
    private IndexerService indexerService;

    @PostMapping
    public ResponseEntity<IndexResponse> indexJsonDocuments(@RequestBody IndexRequest request) {
        
        final String requestId = request.getRequestId();
        final String clientId = request.getClientId();
        
        LOGGER.debug("[{}] Received JSON index request: clientId={}", requestId, clientId);
        
        // Validate request
        IndexResponse 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);
                IndexResponse response = new IndexResponse(requestId, Constants.STATUS_ERROR, "Client not found");
                return ResponseEntity.badRequest().body(response);
            }

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

            if (request.getData() == null || request.getData().isEmpty()) {
                LOGGER.warn("[{}] No document data provided for JSON indexing", requestId);
                IndexResponse response = new IndexResponse(requestId, Constants.STATUS_ERROR, "No document data provided");
                return ResponseEntity.badRequest().body(response);
            }

            List<Map<String, Object>> data = request.getData();
            
            LOGGER.debug("[{}] Converting and indexing {} JSON document(s)", 
                        requestId, data.size());

            int docCount = indexerService.processDocuments(client, data, true); // force reindexing
            
            IndexResponse response = new IndexResponse(requestId, Constants.STATUS_SUCCESS, "JSON indexing completed successfully");
            response.setIndexed(docCount);

            LOGGER.info("[{}] JSON indexing successful: clientId={}, collection={}", 
                       requestId, clientId, client.getCollection());

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            LOGGER.error("[{}] JSON indexing failed: {}", requestId, e.getMessage(), e);
            IndexResponse response = new IndexResponse(requestId, Constants.STATUS_ERROR, "JSON indexing failed: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * Validates the JSON index request
     * @param request the request to validate
     * @return IndexResponse with error if validation fails, null if valid
     */
    private IndexResponse validateRequest(IndexRequest request) {
        if (request.getRequestId() == null || request.getRequestId().trim().isEmpty()) {
            LOGGER.warn("JSON index request missing requestId");
            return new IndexResponse(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 IndexResponse(request.getRequestId(), Constants.STATUS_ERROR, "ClientId is required");
        }
        return null;
    }

}