package com.bizcare.agent;

import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import java.util.*;

@RestController @RequestMapping("/api/shop") @RequiredArgsConstructor
class ShopController {
    private final CrudService crud;
    @GetMapping({"/bbs","/stocks","/opens","/settlements","/fareboxes","/indocs","/returns","/scans"})
    ApiResponse list(HttpServletRequest r,@AuthenticationPrincipal JwtUser u,@RequestParam Map<String,String> f,@RequestParam(defaultValue="0") int page,@RequestParam(defaultValue="30") int size) {
        Map<String,String> scoped=new HashMap<>(f); Class<? extends BaseEntity> type=type(r.getRequestURI());
        if(type!=BbsPost.class && u.getCompanyId()!=null) scoped.put("outcompanyId",u.getCompanyId().toString());
        return ApiResponse.ok(crud.list(type,u,scoped,page,size));
    }
    @GetMapping("/company") ApiResponse company(@AuthenticationPrincipal JwtUser u) {
        if(u.getCompanyId()==null) return ApiResponse.fail("소속 매장이 없습니다."); return ApiResponse.ok(crud.get(Company.class,u.getCompanyId(),u));
    }
    @PutMapping("/company") ApiResponse companyPut(@AuthenticationPrincipal JwtUser u,@RequestBody Map<String,Object> body) {
        if(u.getCompanyId()==null) return ApiResponse.fail("소속 매장이 없습니다."); return ApiResponse.ok(crud.update(Company.class,u.getCompanyId(),body,u));
    }
    @PostMapping("/scans") ApiResponse scan(@AuthenticationPrincipal JwtUser u,@RequestBody Map<String,Object> body) {
        body.put("outcompanyId",u.getCompanyId()); return ApiResponse.ok(crud.create(ScanDoc.class,body,u));
    }
    @PutMapping("/scans/{id}") ApiResponse scanPut(@AuthenticationPrincipal JwtUser u,@PathVariable Long id,@RequestBody Map<String,Object> body) { return ApiResponse.ok(crud.update(ScanDoc.class,id,body,u)); }
    @SuppressWarnings("unchecked") private <T extends BaseEntity> Class<T> type(String uri) {
        if(uri.contains("stocks"))return (Class<T>)Stock.class;if(uri.contains("opens"))return (Class<T>)OpenRecord.class;if(uri.contains("settlements"))return (Class<T>)SettlementMonth.class;
        if(uri.contains("fareboxes"))return (Class<T>)Farebox.class;if(uri.contains("indocs"))return (Class<T>)IncompleteDoc.class;if(uri.contains("returns"))return (Class<T>)UnreturnedPhone.class;if(uri.contains("scans"))return (Class<T>)ScanDoc.class;return (Class<T>)BbsPost.class;
    }
}
