package com.comet.search.controller;

import com.comet.search.model.SearchRequest;
import com.comet.search.model.SearchResult;
import com.comet.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class SearchController {

    @Autowired
    private SearchService searchService;

    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestParam String username, @RequestParam String password) {
        Map<String, Object> response = new HashMap<>();
        // Simple hardcoded login for demonstration
        if (("admin".equals(username) && "admin123".equals(password)) || 
            ("user".equals(username) && "user123".equals(password))) {
            response.put("success", true);
            response.put("role", username);
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            response.put("message", "Invalid username or password");
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PostMapping("/search")
    public ResponseEntity<Map<String, Object>> search(@ModelAttribute SearchRequest request) {
        Map<String, Object> response = new HashMap<>();

        if (request.isEmpty()) {
            response.put("success", false);
            response.put("message", "Please enter at least one search criteria.");
            return ResponseEntity.ok(response); // Return 200 with success=false like PHP did
        }

        try {
            List<SearchResult> results = searchService.performAdvancedSearch(request);
            
            // Encode UIDs before sending to frontend as the PHP code did
            for (SearchResult res : results) {
                if (res.getUid() != null) {
                    res.setUid(Base64.getEncoder().encodeToString(res.getUid().getBytes()));
                }
            }
            
            response.put("success", true);
            response.put("results", results);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "An error occurred: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
}
