package com.mvrent.carrental.controller;

import com.mvrent.carrental.model.Organization;
import com.mvrent.carrental.model.SystemConfig;
import com.mvrent.carrental.service.ConfigService;
import com.mvrent.carrental.web.ConfigForm;
import com.mvrent.carrental.web.OrgForm;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/** JSON API backing the AJAX Settings forms. */
@RestController
@RequestMapping("/admin/api/settings")
@RequiredArgsConstructor
@PreAuthorize("hasRole('ADMIN') or hasAuthority('MANAGE_CONFIG')")
public class AdminSettingsApiController {

    private final ConfigService configService;

    @PostMapping("/organization")
    public ResponseEntity<?> saveOrganization(@RequestBody OrgForm f) {
        if (f.name() == null || f.name().isBlank()) {
            return ResponseEntity.badRequest().body(Map.of("ok", false, "message", "Organization name is required"));
        }
        Organization org = Organization.builder()
                .name(f.name().trim())
                .legalName(f.legalName())
                .logoUrl(f.logoUrl())
                .address(f.address())
                .gstNumber(f.gstNumber())
                .contactEmail(f.contactEmail())
                .phone(f.phone())
                .currencyCode(blankToDefault(f.currencyCode(), "INR"))
                .build();
        configService.saveOrganization(org);
        return ResponseEntity.ok(Map.of("ok", true));
    }

    @PostMapping("/config")
    public ResponseEntity<?> saveConfig(@RequestBody ConfigForm f) {
        SystemConfig cfg = SystemConfig.builder()
                .currencyCode(blankToDefault(f.currencyCode(), "INR"))
                .defaultTaxPercent(f.defaultTaxPercent())
                .defaultCommissionPercent(f.defaultCommissionPercent())
                .defaultDriverDailyCharge(f.defaultDriverDailyCharge())
                .invoicePrefix(blankToDefault(f.invoicePrefix(), "INV"))
                .settlementCycle(f.settlementCycle())
                .build();
        configService.saveSystemConfig(cfg);
        return ResponseEntity.ok(Map.of("ok", true));
    }

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