package com.mvrent.carrental.controller;

import com.mvrent.carrental.model.MaintenanceRecord;
import com.mvrent.carrental.model.MaintenanceStatus;
import com.mvrent.carrental.service.MaintenanceService;
import com.mvrent.carrental.web.MaintenanceDto;
import com.mvrent.carrental.web.MaintenanceForm;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

/** JSON API backing the AJAX Maintenance screen. */
@RestController
@RequestMapping("/admin/api/maintenance")
@RequiredArgsConstructor
@PreAuthorize("hasRole('ADMIN') or hasAuthority('MANAGE_FLEET')")
public class AdminMaintenanceApiController {

    private final MaintenanceService maintenanceService;

    @GetMapping
    public List<MaintenanceDto> list(@RequestParam(required = false) Long carId) {
        var records = carId != null ? maintenanceService.findByCar(carId) : maintenanceService.findAll();
        return records.stream().map(MaintenanceDto::from).toList();
    }

    @GetMapping("/{id}")
    public MaintenanceDto get(@PathVariable Long id) {
        return MaintenanceDto.from(maintenanceService.findById(id));
    }

    @PostMapping
    public ResponseEntity<?> save(@RequestBody MaintenanceForm f) {
        if (f.carId() == null) return bad("Please select a car");
        if (f.type() == null) return bad("Please select a work type");

        MaintenanceRecord r = f.id() != null ? maintenanceService.findById(f.id()) : new MaintenanceRecord();
        r.setType(f.type());
        r.setStatus(f.status() != null ? f.status() : MaintenanceStatus.COMPLETED);
        r.setServiceDate(f.serviceDate());
        r.setOdometer(f.odometer());
        r.setCost(f.cost());
        r.setGarage(trim(f.garage()));
        r.setNotes(trim(f.notes()));
        r.setNextServiceDate(f.nextServiceDate());
        r.setNextServiceOdometer(f.nextServiceOdometer());

        MaintenanceRecord saved = maintenanceService.save(r, f.carId());
        return ResponseEntity.ok(Map.of("ok", true, "id", saved.getId()));
    }

    @PostMapping("/{id}/delete")
    public ResponseEntity<?> delete(@PathVariable Long id) {
        maintenanceService.delete(id);
        return ResponseEntity.ok(Map.of("ok", true));
    }

    private static String trim(String s) { return s == null || s.isBlank() ? null : s.trim(); }

    private static ResponseEntity<Map<String, Object>> bad(String m) {
        return ResponseEntity.badRequest().body(Map.of("ok", false, "message", m));
    }
}
