package com.magistr.app.controller;

import com.magistr.app.config.auth.RequireRoles;
import com.magistr.app.model.LifecycleEntity;
import com.magistr.app.model.Role;
import com.magistr.app.model.Equipment;
import com.magistr.app.repository.EquipmentRepository;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/equipments")
@RequireRoles({Role.ADMIN, Role.EDUCATION_OFFICE})
public class EquipmentController {

    private final EquipmentRepository equipmentRepository;

    public EquipmentController(EquipmentRepository equipmentRepository) {
        this.equipmentRepository = equipmentRepository;
    }

    @GetMapping
    public List<Equipment> getAllEquipments(@RequestParam(defaultValue = "false") boolean includeArchived) {
        return includeArchived ? equipmentRepository.findAll() : equipmentRepository.findByStatusNot(LifecycleEntity.STATUS_ARCHIVED);
    }

    @PostMapping
    public ResponseEntity<?> createEquipment(@RequestBody Map<String, String> request) {
        String name = request.get("name");
        if (name == null || name.isBlank()) {
            return ResponseEntity.badRequest().body(Map.of("message", "Название обязательно"));
        }
        if (equipmentRepository.findByName(name.trim()).isPresent()) {
            return ResponseEntity.badRequest().body(Map.of("message", "Оборудование с таким названием уже существует"));
        }

        Equipment equipment = new Equipment();
        equipment.setName(name.trim());
        equipmentRepository.save(equipment);

        return ResponseEntity.ok(equipment);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteEquipment(@PathVariable Long id) {
        Equipment equipment = equipmentRepository.findById(id).orElse(null);
        if (equipment == null) {
            return ResponseEntity.notFound().build();
        }
        equipment.archive("Оборудование архивировано");
        equipmentRepository.save(equipment);
        return ResponseEntity.ok(Map.of("message", "Оборудование архивировано"));
    }

    @PostMapping("/{id}/restore")
    public ResponseEntity<?> restoreEquipment(@PathVariable Long id) {
        Equipment equipment = equipmentRepository.findById(id).orElse(null);
        if (equipment == null) {
            return ResponseEntity.notFound().build();
        }
        equipment.restore();
        equipmentRepository.save(equipment);
        return ResponseEntity.ok(equipment);
    }
}
