package com.zioinfo.mall.controller;

import com.zioinfo.mall.ai.OllamaClient;
import com.zioinfo.mall.common.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

/**
 * 매장 운영 API — /api/mall/store-ops
 * 매장 재고·배송·주문처리·서지가격·타임슬롯·직원 운영
 * 25개 엔드포인트
 */
@RestController
@RequestMapping("/api/mall/store-ops")
@RequiredArgsConstructor
public class StoreOperationsController {

    private final OllamaClient ollama;

    // ── 1. 매장 목록 (운영 현황 포함) ─────────────────────────
    @GetMapping("/stores")
    public ApiResponse<?> getAllStores() {
        List<Map<String, Object>> stores = List.of(
            Map.of("id", 1L, "name", "Montvale Main", "status", "OPEN", "pendingOrders", 8, "todayRevenue", 1245.00,
                "staffOnDuty", 4, "inventoryHealth", "GOOD", "zip", "07645"),
            Map.of("id", 2L, "name", "Glen Rock Branch", "status", "OPEN", "pendingOrders", 5, "todayRevenue", 987.00,
                "staffOnDuty", 3, "inventoryHealth", "LOW_STOCK", "zip", "07452"),
            Map.of("id", 3L, "name", "Fair Lawn Express", "status", "OPEN", "pendingOrders", 11, "todayRevenue", 876.00,
                "staffOnDuty", 3, "inventoryHealth", "GOOD", "zip", "07410"),
            Map.of("id", 4L, "name", "Allendale Boutique", "status", "OPEN", "pendingOrders", 3, "todayRevenue", 654.00,
                "staffOnDuty", 2, "inventoryHealth", "GOOD", "zip", "07401"),
            Map.of("id", 5L, "name", "Park Ridge Studio", "status", "CLOSED", "pendingOrders", 0, "todayRevenue", 0.00,
                "staffOnDuty", 0, "inventoryHealth", "N/A", "zip", "07458")
        );
        return ApiResponse.ok(Map.of("stores", stores, "openCount", 4, "closedCount", 1, "totalPendingOrders", 27));
    }

    // ── 2. 매장 대시보드 ───────────────────────────────────────
    @GetMapping("/stores/{id}/dashboard")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<?> getStoreDashboard(@PathVariable Long id) {
        return ApiResponse.ok(Map.of(
            "storeId", id,
            "storeName", "Store #" + id,
            "today", Map.of("orders", 23, "revenue", 1847.00, "deliveries", 19, "refunds", 1),
            "inventory", Map.of("totalSKUs", 45, "lowStock", 3, "outOfStock", 0, "turnoverRate", "87%"),
            "staffMetrics", Map.of("onDuty", 3, "deliveriesCompleted", 19, "avgPreparationTime", "14 min"),
            "alerts", List.of(
                Map.of("level", "WARNING", "msg", "Red roses: only 8 units remaining"),
                Map.of("level", "INFO", "msg", "Peak hour starts in 45 minutes — consider surge pricing")
            ),
            "nextTimeslot", Map.of("slot", "3PM-5PM", "capacity", 12, "booked", 9, "available", 3)
        ));
    }

    // ── 3. 운영 시간 변경 ─────────────────────────────────────
    @PutMapping("/stores/{id}/hours")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<?> updateHours(@PathVariable Long id, @RequestBody Map<String, Object> body) {
        String openTime = (String) body.getOrDefault("openTime", "09:00");
        String closeTime = (String) body.getOrDefault("closeTime", "18:00");
        String dayOfWeek = (String) body.getOrDefault("dayOfWeek", "ALL");
        return ApiResponse.ok(Map.of(
            "storeId", id,
            "updated", Map.of("openTime", openTime, "closeTime", closeTime, "dayOfWeek", dayOfWeek),
            "effectiveFrom", LocalDate.now().toString(),
            "message", "Store hours updated successfully"
        ));
    }

    // ── 4. 매장 상태 변경 ─────────────────────────────────────
    @PutMapping("/stores/{id}/status")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<?> updateStatus(@PathVariable Long id, @RequestBody Map<String, Object> body) {
        String status = (String) body.getOrDefault("status", "OPEN");
        String reason = (String) body.getOrDefault("reason", "");
        if (!List.of("OPEN", "CLOSED", "HOLIDAY", "BUSY").contains(status)) {
            return ApiResponse.fail("Invalid status. Use: OPEN, CLOSED, HOLIDAY, BUSY");
        }
        return ApiResponse.ok(Map.of(
            "storeId", id, "newStatus", status, "reason", reason,
            "updatedAt", LocalDateTime.now().toString(),
            "message", "Store #" + id + " is now " + status
        ));
    }

    // ── 5. 매장 재고 현황 ─────────────────────────────────────
    @GetMapping("/stores/{id}/inventory")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<?> getStoreInventory(@PathVariable Long id,
                                             @RequestParam(defaultValue = "false") boolean lowStockOnly) {
        List<Map<String, Object>> items = List.of(
            Map.of("itemId", 1L, "name", "Red Roses", "quantity", 8, "minThreshold", 20, "status", "LOW_STOCK", "lastRestocked", "2026-06-15"),
            Map.of("itemId", 2L, "name", "Sunflowers", "quantity", 45, "minThreshold", 15, "status", "OK", "lastRestocked", "2026-06-16"),
            Map.of("itemId", 3L, "name", "White Lilies", "quantity", 32, "minThreshold", 10, "status", "OK", "lastRestocked", "2026-06-14"),
            Map.of("itemId", 4L, "name", "Pink Peonies", "quantity", 5, "minThreshold", 10, "status", "LOW_STOCK", "lastRestocked", "2026-06-13"),
            Map.of("itemId", 5L, "name", "Baby's Breath", "quantity", 120, "minThreshold", 30, "status", "OK", "lastRestocked", "2026-06-16"),
            Map.of("itemId", 6L, "name", "Purple Iris", "quantity", 0, "minThreshold", 8, "status", "OUT_OF_STOCK", "lastRestocked", "2026-06-10")
        );
        List<Map<String, Object>> result = lowStockOnly
            ? items.stream().filter(m -> !m.get("status").equals("OK")).toList()
            : items;
        return ApiResponse.ok(Map.of("storeId", id, "inventory", result, "lowStockCount", 2, "outOfStockCount", 1));
    }

    // ── 6. 재고 수량 업데이트 ─────────────────────────────────
    @PutMapping("/stores/{id}/inventory/{itemId}")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<?> updateInventoryItem(@PathVariable Long id, @PathVariable Long itemId,
                                               @RequestBody Map<String, Object> body) {
        int quantity = ((Number) body.getOrDefault("quantity", 0)).intValue();
        String note = (String) body.getOrDefault("note", "Manual update");
        return ApiResponse.ok(Map.of(
            "storeId", id, "itemId", itemId, "newQuantity", quantity,
            "note", note, "updatedAt", LocalDateTime.now().toString(),
            "updatedBy", "manager"
        ));
    }

    // ── 7. 매장간 재고 이양 ───────────────────────────────────
    @PostMapping("/stores/{id}/inventory/transfer")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<?> transferInventory(@PathVariable Long id, @RequestBody Map<String, Object> body) {
        Long targetStoreId = ((Number) body.getOrDefault("targetStoreId", 2)).longValue();
        Long itemId = ((Number) body.getOrDefault("itemId", 1)).longValue();
        int quantity = ((Number) body.getOrDefault("quantity", 10)).intValue();
        String prompt = "Should we transfer " + quantity + " units of item #" + itemId
            + " from store #" + id + " to store #" + targetStoreId
            + "? Consider freshness, transit time (typically 30-60 min), and receiving store demand. Quick yes/no with brief reasoning.";
        String aiAdvice = ollama.generate(prompt);
        if (aiAdvice.isEmpty()) {
            aiAdvice = "Transfer approved: Stock levels at source are sufficient and destination needs replenishment.";
        }
        return ApiResponse.ok(Map.of(
            "transferId", "TRF-" + System.currentTimeMillis(),
            "fromStore", id, "toStore", targetStoreId,
            "itemId", itemId, "quantity", quantity,
            "status", "APPROVED", "aiAdvice", aiAdvice,
            "estimatedArrival", LocalTime.now().plusMinutes(45).toString(),
            "createdAt", LocalDateTime.now().toString()
        ));
    }

    // ── 8. 배송 구역 조회 ─────────────────────────────────────
    @GetMapping("/stores/{id}/delivery-zones")
    public ApiResponse<?> getDeliveryZones(@PathVariable Long id) {
        List<Map<String, Object>> zones = List.of(
            Map.of("zoneId", 1L, "name", "Montvale Local", "zips", List.of("07645"), "deliveryFee", 0.00, "freeDelivery", true, "estimatedMin", 30),
            Map.of("zoneId", 2L, "name", "Bergen County North", "zips", List.of("07401", "07452", "07458"), "deliveryFee", 8.99, "freeDelivery", false, "estimatedMin", 45),
            Map.of("zoneId", 3L, "name", "Bergen County South", "zips", List.of("07410", "07663", "07075"), "deliveryFee", 12.99, "freeDelivery", false, "estimatedMin", 55),
            Map.of("zoneId", 4L, "name", "Extended NJ", "zips", List.of("07020", "07035", "07055"), "deliveryFee", 18.99, "freeDelivery", false, "estimatedMin", 70)
        );
        return ApiResponse.ok(Map.of("storeId", id, "zones", zones, "totalZones", zones.size()));
    }

    // ── 9. 배송 구역 수정 ─────────────────────────────────────
    @PutMapping("/stores/{id}/delivery-zones")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<?> updateDeliveryZones(@PathVariable Long id, @RequestBody Map<String, Object> body) {
        return ApiResponse.ok(Map.of(
            "storeId", id, "status", "UPDATED",
            "changes", body, "updatedAt", LocalDateTime.now().toString()
        ));
    }

    // ── 10. 배송 불가 날짜 설정 ───────────────────────────────
    @PostMapping("/stores/{id}/blackout")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<?> setBlackoutDate(@PathVariable Long id, @RequestBody Map<String, Object> body) {
        String date = (String) body.getOrDefault("date", LocalDate.now().plusDays(1).toString());
        String reason = (String) body.getOrDefault("reason", "Store closure");
        boolean affectsDelivery = (boolean) body.getOrDefault("affectsDelivery", true);
        return ApiResponse.ok(Map.of(
            "storeId", id, "blackoutDate", date, "reason", reason,
            "affectsDelivery", affectsDelivery,
            "affectedOrders", 0,
            "message", "Blackout date set. Customers will see delivery unavailable for " + date
        ));
    }

    // ── 11. 배송 기사 목록 ─────────────────────────────────────
    @GetMapping("/stores/{id}/drivers")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<?> getDrivers(@PathVariable Long id) {
        List<Map<String, Object>> drivers = List.of(
            Map.of("driverId", 1L, "name", "Mike Johnson", "status", "ON_ROUTE", "deliveriesToday", 8, "rating", 4.9, "phone", "***-***-1234"),
            Map.of("driverId", 2L, "name", "Sarah Kim", "status", "AVAILABLE", "deliveriesToday", 5, "rating", 4.8, "phone", "***-***-5678"),
            Map.of("driverId", 3L, "name", "Carlos Rivera", "status", "ON_ROUTE", "deliveriesToday", 7, "rating", 4.7, "phone", "***-***-9012"),
            Map.of("driverId", 4L, "name", "Emma Davis", "status", "OFF_DUTY", "deliveriesToday", 0, "rating", 4.9, "phone", "***-***-3456")
        );
        return ApiResponse.ok(Map.of("storeId", id, "drivers", drivers, "availableCount", 1, "onRouteCount", 2));
    }

    // ── 12. 기사 등록 ─────────────────────────────────────────
    @PostMapping("/stores/{id}/drivers")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<?> addDriver(@PathVariable Long id, @RequestBody Map<String, Object> body) {
        String name = (String) body.getOrDefault("name", "New Driver");
        String phone = (String) body.getOrDefault("phone", "");
        String vehicleType = (String) body.getOrDefault("vehicleType", "CAR");
        return ApiResponse.ok(Map.of(
            "driverId", System.currentTimeMillis() % 10000,
            "storeId", id, "name", name, "vehicleType", vehicleType,
            "status", "AVAILABLE", "createdAt", LocalDateTime.now().toString(),
            "message", "Driver registered. Please ensure background check is completed."
        ));
    }

    // ── 13. 오늘 배송 경로 최적화 ─────────────────────────────
    @GetMapping("/stores/{id}/routes")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<?> getOptimizedRoutes(@PathVariable Long id) {
        List<Map<String, Object>> routes = List.of(
            Map.of("driver", "Mike Johnson", "stops", List.of(
                Map.of("order", "ORD-1001", "zip", "07645", "address", "123 Main St", "time", "2:00-2:30 PM", "status", "DELIVERED"),
                Map.of("order", "ORD-1002", "zip", "07645", "address", "456 Oak Ave", "time", "2:30-3:00 PM", "status", "EN_ROUTE"),
                Map.of("order", "ORD-1003", "zip", "07452", "address", "789 Elm Rd", "time", "3:30-4:00 PM", "status", "PENDING")
            ), "totalDistance", "12.4 mi", "estimatedComplete", "4:00 PM"),
            Map.of("driver", "Carlos Rivera", "stops", List.of(
                Map.of("order", "ORD-1004", "zip", "07401", "address", "321 Pine Ln", "time", "1:30-2:00 PM", "status", "DELIVERED"),
                Map.of("order", "ORD-1005", "zip", "07410", "address", "654 Maple Dr", "time", "2:45-3:15 PM", "status", "PENDING")
            ), "totalDistance", "18.7 mi", "estimatedComplete", "3:15 PM")
        );
        return ApiResponse.ok(Map.of("storeId", id, "routes", routes, "optimizedAt", LocalDateTime.now().toString(), "estimatedSavings", "23% less mileage vs. unoptimized"));
    }

    // ── 14. 처리 대기 주문 ─────────────────────────────────────
    @GetMapping("/stores/{id}/orders/pending")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<?> getPendingOrders(@PathVariable Long id) {
        List<Map<String, Object>> pending = List.of(
            Map.of("orderId", "ORD-1008", "product", "Red Rose Bouquet", "qty", 1, "deliveryTime", "3:00-5:00 PM",
                "zip", "07645", "minutesUntilDeadline", 90, "priority", "HIGH"),
            Map.of("orderId", "ORD-1009", "product", "Sunflower Bundle", "qty", 2, "deliveryTime", "4:00-6:00 PM",
                "zip", "07452", "minutesUntilDeadline", 150, "priority", "NORMAL"),
            Map.of("orderId", "ORD-1010", "product", "White Lily Arrangement", "qty", 1, "deliveryTime", "5:00-7:00 PM",
                "zip", "07401", "minutesUntilDeadline", 210, "priority", "NORMAL"),
            Map.of("orderId", "ORD-1011", "product", "Wedding Bridal Package", "qty", 1, "deliveryTime", "2:00-3:00 PM",
                "zip", "07645", "minutesUntilDeadline", 30, "priority", "URGENT")
        );
        return ApiResponse.ok(Map.of("storeId", id, "pendingOrders", pending, "urgentCount", 1, "totalPending", pending.size()));
    }

    // ── 15. 주문 수락 ─────────────────────────────────────────
    @PutMapping("/stores/{id}/orders/{orderId}/accept")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<?> acceptOrder(@PathVariable Long id, @PathVariable String orderId,
                                       @RequestBody(required = false) Map<String, Object> body) {
        String assignedDriver = body != null ? (String) body.getOrDefault("driverId", "auto-assign") : "auto-assign";
        return ApiResponse.ok(Map.of(
            "orderId", orderId, "storeId", id,
            "status", "ACCEPTED", "assignedDriver", assignedDriver,
            "estimatedPrepTime", "15 min",
            "message", "Order accepted. Preparation should begin immediately."
        ));
    }

    // ── 16. 준비 시작 ─────────────────────────────────────────
    @PutMapping("/stores/{id}/orders/{orderId}/start-prep")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<?> startPrep(@PathVariable Long id, @PathVariable String orderId) {
        return ApiResponse.ok(Map.of(
            "orderId", orderId, "storeId", id, "status", "PREPARING",
            "prepStartedAt", LocalDateTime.now().toString(),
            "estimatedReadyAt", LocalDateTime.now().plusMinutes(15).toString(),
            "message", "Preparation started. Timer running — target 15 min."
        ));
    }

    // ── 17. 품질 사진 업로드 ───────────────────────────────────
    @PostMapping("/stores/{id}/orders/{orderId}/photo")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<?> uploadQualityPhoto(@PathVariable Long id, @PathVariable String orderId,
                                              @RequestBody Map<String, Object> body) {
        String photoUrl = (String) body.getOrDefault("photoUrl", "/uploads/proof-of-quality/" + orderId + ".jpg");
        String note = (String) body.getOrDefault("note", "");
        return ApiResponse.ok(Map.of(
            "orderId", orderId, "storeId", id,
            "photoUrl", photoUrl, "note", note,
            "uploadedAt", LocalDateTime.now().toString(),
            "status", "PHOTO_VERIFIED",
            "message", "Quality photo saved. Customer will receive before delivery."
        ));
    }

    // ── 18. 서지 가격 현황 ─────────────────────────────────────
    @GetMapping("/stores/{id}/surge-pricing")
    public ApiResponse<?> getSurgePricing(@PathVariable Long id) {
        boolean isSurge = LocalTime.now().isAfter(LocalTime.of(16, 0)) && LocalTime.now().isBefore(LocalTime.of(19, 0));
        return ApiResponse.ok(Map.of(
            "storeId", id,
            "isSurgeActive", isSurge,
            "surgeMultiplier", isSurge ? 1.25 : 1.0,
            "surgePeriods", List.of(
                Map.of("name", "Evening Rush", "start", "4:00 PM", "end", "7:00 PM", "multiplier", 1.25),
                Map.of("name", "Valentine's Day", "start", "Feb 13 All Day", "end", "Feb 14 Close", "multiplier", 1.40),
                Map.of("name", "Mother's Day Weekend", "start", "Fri", "end", "Sun", "multiplier", 1.35)
            ),
            "currentStatus", isSurge ? "SURGE ACTIVE — 25% delivery premium" : "Normal pricing"
        ));
    }

    // ── 19. 서지 가격 설정 ─────────────────────────────────────
    @PutMapping("/stores/{id}/surge-pricing")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<?> setSurgePricing(@PathVariable Long id, @RequestBody Map<String, Object> body) {
        boolean enabled = (boolean) body.getOrDefault("enabled", false);
        double multiplier = ((Number) body.getOrDefault("multiplier", 1.25)).doubleValue();
        String reason = (String) body.getOrDefault("reason", "High demand");
        if (multiplier < 1.0 || multiplier > 2.0) {
            return ApiResponse.fail("Multiplier must be between 1.0 and 2.0");
        }
        return ApiResponse.ok(Map.of(
            "storeId", id, "surgeEnabled", enabled, "multiplier", multiplier,
            "reason", reason, "effectiveAt", LocalDateTime.now().toString(),
            "message", enabled ? "Surge pricing activated at " + (int)((multiplier - 1) * 100) + "% premium" : "Surge pricing deactivated"
        ));
    }

    // ── 20. 타임슬롯 가용성 ───────────────────────────────────
    @GetMapping("/stores/{id}/timeslots")
    public ApiResponse<?> getTimeslots(@PathVariable Long id,
                                        @RequestParam(defaultValue = "") String date) {
        String targetDate = date.isEmpty() ? LocalDate.now().toString() : date;
        List<Map<String, Object>> slots = List.of(
            Map.of("slot", "9AM-11AM", "capacity", 10, "booked", 3, "available", 7, "status", "AVAILABLE"),
            Map.of("slot", "11AM-1PM", "capacity", 15, "booked", 14, "available", 1, "status", "ALMOST_FULL"),
            Map.of("slot", "1PM-3PM", "capacity", 15, "booked", 15, "available", 0, "status", "FULL"),
            Map.of("slot", "3PM-5PM", "capacity", 12, "booked", 9, "available", 3, "status", "AVAILABLE"),
            Map.of("slot", "5PM-7PM", "capacity", 12, "booked", 7, "available", 5, "status", "AVAILABLE")
        );
        return ApiResponse.ok(Map.of("storeId", id, "date", targetDate, "timeslots", slots));
    }

    // ── 21. 슬롯 용량 변경 ─────────────────────────────────────
    @PutMapping("/stores/{id}/timeslots/{slot}/capacity")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<?> updateSlotCapacity(@PathVariable Long id, @PathVariable String slot,
                                              @RequestBody Map<String, Object> body) {
        int newCapacity = ((Number) body.getOrDefault("capacity", 15)).intValue();
        String date = (String) body.getOrDefault("date", LocalDate.now().toString());
        return ApiResponse.ok(Map.of(
            "storeId", id, "slot", slot, "date", date,
            "newCapacity", newCapacity, "updatedAt", LocalDateTime.now().toString()
        ));
    }

    // ── 22. 직원 스케줄 ───────────────────────────────────────
    @GetMapping("/stores/{id}/staff")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<?> getStaffSchedule(@PathVariable Long id,
                                            @RequestParam(defaultValue = "") String date) {
        String targetDate = date.isEmpty() ? LocalDate.now().toString() : date;
        List<Map<String, Object>> staff = List.of(
            Map.of("staffId", 1L, "name", "Jennifer Lee", "role", "Lead Florist", "shift", "8AM-4PM", "status", "ON_DUTY"),
            Map.of("staffId", 2L, "name", "Tom Garcia", "role", "Florist", "shift", "9AM-5PM", "status", "ON_DUTY"),
            Map.of("staffId", 3L, "name", "Amy Chen", "role", "Driver", "shift", "10AM-6PM", "status", "ON_ROUTE"),
            Map.of("staffId", 4L, "name", "David Park", "role", "Counter", "shift", "12PM-8PM", "status", "ON_DUTY"),
            Map.of("staffId", 5L, "name", "Rachel Brown", "role", "Driver", "shift", "1PM-9PM", "status", "BREAK")
        );
        return ApiResponse.ok(Map.of("storeId", id, "date", targetDate, "staff", staff, "onDutyCount", 4));
    }

    // ── 23. 매장 알림 발송 ─────────────────────────────────────
    @PostMapping("/stores/{id}/alert")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<?> sendStoreAlert(@PathVariable Long id, @RequestBody Map<String, Object> body) {
        String message = (String) body.getOrDefault("message", "Attention staff");
        String channel = (String) body.getOrDefault("channel", "ALL");
        String priority = (String) body.getOrDefault("priority", "NORMAL");
        return ApiResponse.ok(Map.of(
            "storeId", id, "alertId", "ALT-" + System.currentTimeMillis(),
            "message", message, "channel", channel, "priority", priority,
            "sentAt", LocalDateTime.now().toString(),
            "recipientCount", channel.equals("ALL") ? 5 : 2,
            "status", "DELIVERED"
        ));
    }

    // ── 24. 일일 마감 리포트 ───────────────────────────────────
    @GetMapping("/stores/{id}/reports/daily")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<?> getDailyReport(@PathVariable Long id,
                                          @RequestParam(defaultValue = "") String date) {
        String reportDate = date.isEmpty() ? LocalDate.now().toString() : date;
        String prompt = "Generate a concise daily closing report summary for a flower shop. Revenue: $1,847, Orders: 23, Deliveries: 21, Refunds: 1, Top product: Red Roses. Keep it professional and under 100 words.";
        String summary = ollama.generate(prompt);
        if (summary.isEmpty()) {
            summary = "Strong day with $1,847 in revenue across 23 orders. 21/23 deliveries completed on time (91% rate). Red Roses led sales. 1 refund processed. Inventory status: red roses low, recommend restocking before opening tomorrow.";
        }
        return ApiResponse.ok(Map.of(
            "storeId", id, "date", reportDate,
            "summary", Map.of("revenue", 1847.00, "orders", 23, "deliveries", 21, "onTimeRate", "91.3%", "refunds", 1, "topProduct", "Red Roses"),
            "aiSummary", summary,
            "nextDayPrep", List.of("Restock red roses (8 units left)", "Driver schedule confirmed for tomorrow", "Check 3 pending next-day orders")
        ));
    }

    // ── 25. 전체 매장 네트워크 현황 ───────────────────────────
    @GetMapping("/network")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<?> getNetworkStatus() {
        Map<String, Object> network = new LinkedHashMap<>();
        network.put("networkHealth", "GOOD");
        network.put("totalStores", 5);
        network.put("openStores", 4);
        network.put("closedStores", 1);
        network.put("networkRevenue", Map.of("today", 3762.00, "week", 24500.00, "month", 94500.00));
        network.put("totalPendingOrders", 27);
        network.put("urgentOrders", 2);
        network.put("driverUtilization", "78%");
        network.put("inventoryAlerts", List.of(
            Map.of("store", "Montvale Main", "item", "Red Roses", "qty", 8, "severity", "HIGH"),
            Map.of("store", "Glen Rock Branch", "item", "Pink Peonies", "qty", 5, "severity", "HIGH")
        ));
        network.put("systemStatus", "ALL_SYSTEMS_OPERATIONAL");
        network.put("generatedAt", LocalDateTime.now().toString());
        return ApiResponse.ok(network);
    }
}
