package com.erp.controller;

import com.erp.dto.ApiResponse;
import com.erp.service.DriverService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.*;

@RestController
@RequestMapping("/api/driver")
@RequiredArgsConstructor
@Slf4j
public class DriverController {
    private final DriverService driverService;

    /** GET /list → 운전자 목록 (admin용 / api_test 호환) */
    @GetMapping("/list")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getDriverList(
            @RequestAttribute("company_code") String companyCode,
            @RequestParam Map<String, Object> params) {
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(driverService.getDriverList(params)));
    }

    /** GET /profile → 운전자 프로필 조회 */
    @GetMapping("/profile")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getDriverProfile(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute(value = "user_id", required = false) String userId) {
        if (userId == null) {
            return ResponseEntity.status(401).body(ApiResponse.error("인증이 필요합니다."));
        }
        Map<String, Object> params = new HashMap<>();
        params.put("company_code", companyCode);
        params.put("user_id", userId);
        Map<String, Object> result = driverService.getDriverProfile(params);
        if (result == null) {
            return ResponseEntity.status(404).body(ApiResponse.error("사용자를 찾을 수 없습니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    /** PUT /profile → 운전자 프로필 수정 */
    @PutMapping("/profile")
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateDriverProfile(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute(value = "user_id", required = false) String userId,
            @RequestBody Map<String, Object> body) {
        if (userId == null) {
            return ResponseEntity.status(401).body(ApiResponse.error("인증이 필요합니다."));
        }
        body.put("company_code", companyCode);
        body.put("user_id", userId);
        driverService.updateDriverProfile(body);
        return ResponseEntity.ok(ApiResponse.success(null, "프로필이 수정되었습니다."));
    }

    /** PUT /status → 차량 상태 변경 (off: 대기, maintenance: 정비) */
    @PutMapping("/status")
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateDriverStatus(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute(value = "user_id", required = false) String userId,
            @RequestBody Map<String, Object> body) {
        if (userId == null) {
            return ResponseEntity.status(401).body(ApiResponse.error("인증이 필요합니다."));
        }
        String status = body.get("status") != null ? String.valueOf(body.get("status")) : null;
        if (status == null || (!status.equals("off") && !status.equals("maintenance"))) {
            return ResponseEntity.status(400).body(
                    ApiResponse.error("유효하지 않은 상태값입니다. (off: 대기, maintenance: 정비)"));
        }
        body.put("user_id", userId);
        driverService.updateDriverStatus(body);
        String msg = "off".equals(status) ? "차량 상태가 대기로 변경되었습니다." : "차량 상태가 정비로 변경되었습니다.";
        return ResponseEntity.ok(ApiResponse.success(null, msg));
    }

    /** DELETE /vehicle → 차량 삭제 (기록 보존) */
    @DeleteMapping("/vehicle")
    public ResponseEntity<ApiResponse<Map<String, Object>>> deleteDriverVehicle(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute(value = "user_id", required = false) String userId) {
        if (userId == null) {
            return ResponseEntity.status(401).body(ApiResponse.error("인증이 필요합니다."));
        }
        Map<String, Object> params = new HashMap<>();
        params.put("user_id", userId);
        driverService.deleteDriverVehicle(params);
        return ResponseEntity.ok(ApiResponse.success(null, "차량이 삭제되었습니다."));
    }

    /** POST /vehicle → 새 차량 등록 */
    @PostMapping("/vehicle")
    public ResponseEntity<ApiResponse<Map<String, Object>>> registerDriverVehicle(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute(value = "user_id", required = false) String userId,
            @RequestBody Map<String, Object> body) {
        if (userId == null) {
            return ResponseEntity.status(401).body(ApiResponse.error("인증이 필요합니다."));
        }
        if (body.get("vehicle_number") == null) {
            return ResponseEntity.status(400).body(ApiResponse.error("차량번호는 필수입니다."));
        }
        body.put("company_code", companyCode);
        body.put("user_id", userId);
        driverService.registerDriverVehicle(body);
        return ResponseEntity.ok(ApiResponse.success(null, "차량이 등록되었습니다."));
    }

    /** DELETE /account → 회원 탈퇴 */
    @DeleteMapping("/account")
    public ResponseEntity<ApiResponse<Map<String, Object>>> deleteDriverAccount(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute(value = "user_id", required = false) String userId) {
        if (userId == null) {
            return ResponseEntity.status(401).body(ApiResponse.error("인증이 필요합니다."));
        }
        Map<String, Object> params = new HashMap<>();
        params.put("user_id", userId);
        driverService.deleteDriverAccount(params);
        return ResponseEntity.ok(ApiResponse.success(null, "회원 탈퇴가 완료되었습니다."));
    }
}
