package com.mvrent.carrental.controller;

import com.mvrent.carrental.model.InspectionCondition;
import com.mvrent.carrental.model.InspectionRecord;
import com.mvrent.carrental.service.InspectionService;
import com.mvrent.carrental.web.InspectionDto;
import com.mvrent.carrental.web.InspectionForm;
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 Inspections screen. */
@RestController
@RequestMapping("/admin/api/inspections")
@RequiredArgsConstructor
@PreAuthorize("hasRole('ADMIN') or hasAuthority('MANAGE_FLEET')")
public class AdminInspectionApiController {

    private final InspectionService inspectionService;

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

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

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

        InspectionRecord r = f.id() != null ? inspectionService.findById(f.id()) : new InspectionRecord();
        r.setType(f.type());
        r.setCondition(f.condition() != null ? f.condition() : InspectionCondition.GOOD);
        r.setInspectionDate(f.inspectionDate());
        r.setInspector(trim(f.inspector()));
        r.setOdometer(f.odometer());
        r.setFuelLevel(f.fuelLevel());
        r.setDamageNotes(trim(f.damageNotes()));
        r.setPhotoUrl(trim(f.photoUrl()));

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

    @PostMapping("/{id}/delete")
    public ResponseEntity<?> delete(@PathVariable Long id) {
        inspectionService.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));
    }
}
