package com.mvrent.carrental.controller;

import com.mvrent.carrental.model.Vendor;
import com.mvrent.carrental.service.VendorService;
import com.mvrent.carrental.web.VendorDto;
import com.mvrent.carrental.web.VendorForm;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

/** JSON API backing the AJAX Manage Vendors screen. */
@RestController
@RequestMapping("/admin/api/vendors")
@RequiredArgsConstructor
@PreAuthorize("hasRole('ADMIN') or hasAuthority('MANAGE_VENDORS')")
public class AdminVendorApiController {

    private final VendorService vendorService;

    @GetMapping
    public List<VendorDto> list() {
        return vendorService.findAll().stream().map(VendorDto::from).toList();
    }

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

    @PostMapping
    public ResponseEntity<?> save(@RequestBody VendorForm f) {
        Map<String, String> errors = new LinkedHashMap<>();
        if (isBlank(f.name())) errors.put("name", "Name is required");
        if (!errors.isEmpty()) {
            return ResponseEntity.badRequest().body(Map.of("ok", false, "errors", errors));
        }

        // Load existing on edit so we don't null out anything outside the form.
        Vendor v = f.id() != null ? vendorService.findById(f.id()) : new Vendor();
        v.setName(trim(f.name()));
        v.setContactPerson(trim(f.contactPerson()));
        v.setPhone(trim(f.phone()));
        v.setEmail(trim(f.email()));
        v.setAddress(trim(f.address()));
        v.setGstNumber(trim(f.gstNumber()));
        v.setSettlementDetails(trim(f.settlementDetails()));
        v.setCommissionPercent(f.commissionPercent());
        v.setActive(f.active() == null || f.active());

        Vendor saved = vendorService.save(v);
        return ResponseEntity.ok(Map.of("ok", true, "vendor", VendorDto.from(saved)));
    }

    @PostMapping("/{id}/delete")
    public ResponseEntity<?> delete(@PathVariable Long id) {
        try {
            vendorService.delete(id);
            return ResponseEntity.ok(Map.of("ok", true));
        } catch (DataIntegrityViolationException ex) {
            return ResponseEntity.badRequest().body(Map.of("ok", false,
                    "message", "Cannot delete — vendor has cars, drivers or a portal login. Deactivate instead."));
        }
    }

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