/**
 * 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.search.controller;

import java.util.List;

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.ClientException;
import com.softcorporation.sandi.search.model.TypeAheadRequest;
import com.softcorporation.sandi.search.model.TypeAheadResponse;
import com.softcorporation.sandi.search.service.TypeAheadService;

@RestController
@RequestMapping("/typeahead")
public class TypeAheadController {

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

    @Autowired
    private ClientService clientService;

    @Autowired
    private TypeAheadService typeAheadService;

    @GetMapping
    public ResponseEntity<TypeAheadResponse> searchGet(
            @RequestParam(required = false) String requestId,
            @RequestParam String clientId,
            @RequestParam(required = false) String searchCollections,
            @RequestParam(required = false) String query) {
        
        LOGGER.debug("[{}] Received GET request: clientId={}", requestId, clientId);
        
        TypeAheadRequest request = new TypeAheadRequest(requestId, clientId);
        request.setSearchCollections(searchCollections);
        request.setQuery(query);
        
        ResponseEntity<TypeAheadResponse> response = performSearch(request);
        
        LOGGER.debug("[{}] GET search response: status={}", requestId, response.getStatusCode());
        
        return response;
    }
    
    /**
     * Validates search request
     * @param request the request to validate
     * @return SearchResponse with error if validation fails, null if valid
     * @throws ClientException 
     */
    private TypeAheadResponse validateRequest(TypeAheadRequest request) {
//        if (request.getRequestId() == null || request.getRequestId().trim().isEmpty()) {
//            LOGGER.warn("Search request missing requestId");
//            return new TypeAheadResponse("MISSING", "ERROR", "RequestId is required");
//        }
        
        if (request.getClientId() == null || request.getClientId().trim().isEmpty()) {
            LOGGER.warn("[{}] Search request missing clientId", request.getRequestId());
            return new TypeAheadResponse("MISSING", "ERROR", "ClientId is required");
        }
        
        return null;
    }

    /**
     * Validates the Client
     * @param request the request to validate
     * @return SearchResponse with error if validation fails, null if valid
     * @throws ClientException 
     */
    private TypeAheadResponse validateClient(TypeAheadRequest request) throws ClientException {
        LOGGER.debug("[{}] Validating client: {}", request.getRequestId(), request.getClientId());
        Client client = clientService.getClient(request.getClientId());
        if (client == null) {
            LOGGER.warn("[{}] Client not found: {}", request.getRequestId(), request.getClientId());
            return new TypeAheadResponse(request.getRequestId(), "ERROR", "Client not found");
        }
        if (!client.isActive()) {
            LOGGER.warn("[{}] Client is inactive: {}", request.getRequestId(), request.getClientId());
            return new TypeAheadResponse(request.getRequestId(), "ERROR", "Client is inactive");
        }
        request.setClient(client);
        
        return null;
    }

    private ResponseEntity<TypeAheadResponse> performSearch(TypeAheadRequest request) {

        // Validate request
    	TypeAheadResponse validationError = validateRequest(request);
        if (validationError != null) {
        	return ResponseEntity.badRequest().body(validationError);
        }

        // Validate client
		try {
			validationError = validateClient(request);
	        if (validationError != null) {
	        	return ResponseEntity.badRequest().body(validationError);
	        }
		} catch (ClientException e) {
            LOGGER.error("[{}] Client: {} Error: {}", request.getRequestId(), request.getClientId(), e.getMessage());
            TypeAheadResponse response = new TypeAheadResponse(request.getRequestId(), "ERROR", "Client error");
            return ResponseEntity.internalServerError().body(response);
		}

        try {
            TypeAheadResponse response = typeAheadService.search(request);
            
            List<?> results = response.getResults();
            LOGGER.debug("[{}] Type Ahead search completed. Results={}", request.getRequestId(), results.size());

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            LOGGER.error("[{}] Search failed: {}", request.getRequestId(), e.getMessage(), e);
            TypeAheadResponse response = new TypeAheadResponse(request.getRequestId(), "ERROR", "Search failed: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
}