package com.erp.controller;

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

import java.util.*;

/**
 * 차량 운행 이력 + 리포트 API
 * Node.js: vehicleTripRoutes.ts (app.use("/api/vehicle-trip", router))
 */
@RestController
@RequestMapping("/api/vehicle-trip")
@RequiredArgsConstructor
@Slf4j
public class VehicleTripController {

    private final VehicleTripService vehicleTripService;

    // ─── 운행 목록 ─────────────────────────────────────────

    /** GET /list — 운행 목록 (alias) */
    @GetMapping("/list")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getVehicleTripListAlias(
            @RequestAttribute("company_code") String companyCode,
            @RequestParam Map<String, Object> params) {
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(vehicleTripService.getTripList(params)));
    }

    /** GET /trips — 운행 이력 목록, 응답: { data, total } */
    @GetMapping("/trips")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getTripList(
            @RequestAttribute("company_code") String companyCode,
            @RequestParam Map<String, Object> params) {
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(vehicleTripService.getTripList(params)));
    }

    /** GET /trips/{tripId} — 운행 상세 (경로 포함) */
    @GetMapping("/trips/{tripId}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getTripDetail(
            @RequestAttribute("company_code") String companyCode,
            @PathVariable String tripId) {
        Map<String, Object> params = new LinkedHashMap<>();
        params.put("company_code", companyCode);
        params.put("trip_id", tripId);
        Map<String, Object> result = vehicleTripService.getTripDetail(params);
        if (result == null) {
            return ResponseEntity.status(404).body(ApiResponse.error("운행 정보를 찾을 수 없습니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(result));
    }

    // ─── 운행 관리 ─────────────────────────────────────────

    /** GET /trip/active — 현재 진행 중 운행 조회 */
    @GetMapping("/trip/active")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getActiveTrip(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId) {
        Map<String, Object> params = new LinkedHashMap<>();
        params.put("company_code", companyCode);
        params.put("user_id", userId);
        return ResponseEntity.ok(ApiResponse.success(vehicleTripService.getActiveTrip(params)));
    }

    /** POST /trip/start — 운행 시작 */
    @PostMapping("/trip/start")
    public ResponseEntity<ApiResponse<Map<String, Object>>> startTrip(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @RequestBody Map<String, Object> body) {
        if (body.get("latitude") == null || body.get("longitude") == null) {
            return ResponseEntity.status(400).body(ApiResponse.error("위치 정보(latitude, longitude)가 필요합니다."));
        }
        body.put("company_code", companyCode);
        body.put("user_id", userId);
        return ResponseEntity.ok(ApiResponse.success(vehicleTripService.startTrip(body), "운행이 시작되었습니다."));
    }

    /** POST /trip/end — 운행 종료 */
    @PostMapping("/trip/end")
    public ResponseEntity<ApiResponse<Map<String, Object>>> endTrip(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @RequestBody Map<String, Object> body) {
        if (body.get("trip_id") == null) {
            return ResponseEntity.status(400).body(ApiResponse.error("tripId가 필요합니다."));
        }
        if (body.get("latitude") == null || body.get("longitude") == null) {
            return ResponseEntity.status(400).body(ApiResponse.error("위치 정보(latitude, longitude)가 필요합니다."));
        }
        body.put("company_code", companyCode);
        body.put("user_id", userId);
        return ResponseEntity.ok(ApiResponse.success(vehicleTripService.endTrip(body), "운행이 종료되었습니다."));
    }

    /** POST /trip/location — 위치 기록 추가 */
    @PostMapping("/trip/location")
    public ResponseEntity<ApiResponse<Map<String, Object>>> addTripLocation(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @RequestBody Map<String, Object> body) {
        if (body.get("trip_id") == null) {
            return ResponseEntity.status(400).body(ApiResponse.error("tripId가 필요합니다."));
        }
        if (body.get("latitude") == null || body.get("longitude") == null) {
            return ResponseEntity.status(400).body(ApiResponse.error("위치 정보(latitude, longitude)가 필요합니다."));
        }
        body.put("company_code", companyCode);
        body.put("user_id", userId);
        return ResponseEntity.ok(ApiResponse.success(vehicleTripService.addLocation(body)));
    }

    /** POST /trip/cancel — 운행 취소 */
    @PostMapping("/trip/cancel")
    public ResponseEntity<ApiResponse<Map<String, Object>>> cancelTrip(
            @RequestAttribute("company_code") String companyCode,
            @RequestBody Map<String, Object> body) {
        if (body.get("trip_id") == null) {
            return ResponseEntity.status(400).body(ApiResponse.error("tripId가 필요합니다."));
        }
        body.put("company_code", companyCode);
        Map<String, Object> result = vehicleTripService.cancelTrip(body);
        if (result == null) {
            return ResponseEntity.status(404).body(ApiResponse.error("취소할 운행을 찾을 수 없습니다."));
        }
        return ResponseEntity.ok(ApiResponse.success(null, "운행이 취소되었습니다."));
    }

    // ─── 리포트 ─────────────────────────────────────────────

    /** GET /reports/summary — 요약 통계 (period: today/week/month/year) */
    @GetMapping("/reports/summary")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getSummaryReport(
            @RequestAttribute("company_code") String companyCode,
            @RequestParam Map<String, Object> params) {
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(vehicleTripService.getSummaryReport(params)));
    }

    /** GET /reports/daily — 일별 통계 */
    @GetMapping("/reports/daily")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getDailyReport(
            @RequestAttribute("company_code") String companyCode,
            @RequestParam Map<String, Object> params) {
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(vehicleTripService.getDailyReport(params)));
    }

    /** GET /reports/weekly — 주별 통계 */
    @GetMapping("/reports/weekly")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getWeeklyReport(
            @RequestAttribute("company_code") String companyCode,
            @RequestParam Map<String, Object> params) {
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(vehicleTripService.getWeeklyReport(params)));
    }

    /** GET /reports/monthly — 월별 통계 */
    @GetMapping("/reports/monthly")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getMonthlyReport(
            @RequestAttribute("company_code") String companyCode,
            @RequestParam Map<String, Object> params) {
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(vehicleTripService.getMonthlyReport(params)));
    }

    /** GET /reports/by-driver — 운전자별 통계 */
    @GetMapping("/reports/by-driver")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getDriverReport(
            @RequestAttribute("company_code") String companyCode,
            @RequestParam Map<String, Object> params) {
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(vehicleTripService.getDriverReport(params)));
    }

    /** GET /reports/by-route — 구간별 통계 */
    @GetMapping("/reports/by-route")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getRouteReport(
            @RequestAttribute("company_code") String companyCode,
            @RequestParam Map<String, Object> params) {
        params.put("company_code", companyCode);
        return ResponseEntity.ok(ApiResponse.success(vehicleTripService.getRouteReport(params)));
    }
}
