package com.escolapios.fctmongo.controller;

import com.escolapios.fctmongo.entity.Convenio;
import com.escolapios.fctmongo.entity.Empresa;
import com.escolapios.fctmongo.service.EmpresaService;
import com.escolapios.fctmongo.repository.EmpresaRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/empresas")
@CrossOrigin(origins = "*")
public class EmpresaController {
    private final EmpresaService empresaService;
    private final EmpresaRepository empresaRepository;

    public EmpresaController(EmpresaService empresaService, EmpresaRepository empresaRepository) { 
        this.empresaService = empresaService; 
        this.empresaRepository = empresaRepository;
    }
    @GetMapping
    public ResponseEntity<List<Empresa>> listar() { return ResponseEntity.ok(empresaService.obtenerTodas()); }

    @GetMapping("/listar")
    public ResponseEntity<Page<Empresa>> listarEmpresas(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(required = false) String texto) {      
        
        Pageable pageable = PageRequest.of(page, 10);
        Page<Empresa> paginaEmpresas;
        
        // 🟢 Si el usuario escribe en el buscador del frontal
        if (texto != null && !texto.trim().isEmpty()) {
            // Buscamos primero por nombre, si no encuentra registros, intentamos por CIF
            paginaEmpresas = empresaRepository.findByNombreContainingIgnoreCase(texto.trim(), pageable);
            if (paginaEmpresas.isEmpty()) {
                paginaEmpresas = empresaRepository.findByCifContainingIgnoreCase(texto.trim(), pageable);
            }
        } else {
            // Listado normal por defecto
            paginaEmpresas = empresaRepository.findAll(pageable);
        }
        return ResponseEntity.ok(paginaEmpresas);
    }

    @PostMapping
    public ResponseEntity<Empresa> crear(@RequestBody Empresa empresa) { 
        return new ResponseEntity<>(empresaService.guardar(empresa), HttpStatus.CREATED); 
    }
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> eliminar(@PathVariable String id) {
        try {
            // 1. Invocamos al servicio para eliminar el documento en MongoDB
            empresaService.eliminar(id);           
            // 2. Retornamos un estado 204 No Content indicando que se borró con éxito
            return ResponseEntity.noContent().build();
        } catch (Exception e) {
            // Retornamos un 500 si ocurre algún problema en el servidor
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    @GetMapping("/{id}")
    public ResponseEntity<Empresa> obtenerPorId(@PathVariable String id) {
        // Buscamos la empresa a través del servicio
        Empresa empresa = empresaService.obtenerPorId(id);
        
        // Si el servicio devuelve la empresa, respondemos 200 OK. Si es null, respondemos 404 NOT FOUND
        if (empresa != null) {
            return ResponseEntity.ok(empresa);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    @PutMapping("/{id}")
    public ResponseEntity<Empresa> actualizar(@PathVariable String id, @RequestBody Empresa empresa) {
        try {
            // 1. Buscamos si la empresa existe antes de intentar sobrescribirla
            Empresa empresaExistente = empresaService.obtenerPorId(id);
            
            if (empresaExistente != null) {
                // 2. Forzamos que el objeto lleve el ID de la URL para asegurar que MongoDB actualice el documento correcto
                empresa.setId(id);
                
                // 3. Guardamos los cambios y devolvemos el objeto actualizado con un estado 200 OK
                Empresa empresaActualizada = empresaService.guardar(empresa);
                return ResponseEntity.ok(empresaActualizada);
            } else {
                // Si el ID de la URL no existe en MongoDB, devolvemos un 404 Not Found
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            // Si ocurre algún fallo en el servidor, devolvemos un 500
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    @GetMapping("/validar-cif")
    public ResponseEntity<Boolean> comprobarCifUnique(@RequestParam String cif) {
        // Retorna true si el CIF ya existe, false si está libre
        return ResponseEntity.ok(empresaService.existePorCif(cif));
    }

}