package com.ga.api.controller.mobile;

import com.ga.api.service.mobile.MobileMeService;
import com.ga.api.service.mobile.MobileMeService.MeSummary;
import com.ga.api.service.mobile.MobileMeService.MobileWithdrawSaveReq;
import com.ga.api.service.mobile.MobileMeService.WithdrawableBalance;
import com.ga.common.model.ApiResponse;
import com.ga.common.model.PageResponse;
import com.ga.core.vo.notice.UserNotificationResp;
import com.ga.core.vo.notice.UserNotificationSearchParam;
import com.ga.core.vo.settle.CommissionStatementResp;
import com.ga.core.vo.settle.CommissionStatementSearchParam;
import com.ga.core.vo.settle.SettleMasterResp;
import com.ga.core.vo.withdraw.WithdrawRequestResp;
import com.ga.core.vo.withdraw.WithdrawRequestSearchParam;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 모바일 PWA 전용 — 토큰의 사용자 본인 데이터만 반환.
 *
 * <p>모든 endpoint 는 인증만 통과하면 사용 가능 (별도 메뉴 권한 없음).
 * agentId / userId 는 서버측에서 토큰 → user 조회로 강제 결정. 클라이언트 파라미터는 무시한다.
 */
@Tag(name = "모바일 셀프 조회")
@RestController
@RequestMapping("/api/mobile/me")
@RequiredArgsConstructor
public class MobileMeController {

    private final MobileMeService service;

    @GetMapping("/summary")
    public ApiResponse<MeSummary> summary() {
        return ApiResponse.ok(service.summary());
    }

    @GetMapping("/statements")
    public ApiResponse<PageResponse<CommissionStatementResp>> statements(
            @ModelAttribute CommissionStatementSearchParam param) {
        return ApiResponse.ok(service.statements(param));
    }

    @GetMapping("/statements/{statementId}")
    public ApiResponse<CommissionStatementResp> statementDetail(@PathVariable Long statementId) {
        return ApiResponse.ok(service.statementDetail(statementId));
    }

    @GetMapping("/statements/{statementId}/download")
    public void downloadStatement(@PathVariable Long statementId, HttpServletResponse response) throws IOException {
        byte[] content = service.downloadStatement(statementId);
        String encoded = URLEncoder.encode("수수료명세서_" + statementId + ".xlsx", StandardCharsets.UTF_8)
                .replace("+", "%20");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encoded);
        response.setContentLength(content.length);
        response.getOutputStream().write(content);
    }

    @GetMapping("/settle-masters")
    public ApiResponse<List<SettleMasterResp>> withdrawableSettleMasters() {
        return ApiResponse.ok(service.withdrawableSettleMasters());
    }

    @GetMapping("/settle-masters/{settleMasterId}/withdrawable-balance")
    public ApiResponse<WithdrawableBalance> withdrawableBalance(@PathVariable Long settleMasterId) {
        return ApiResponse.ok(service.withdrawableBalance(settleMasterId));
    }

    @GetMapping("/withdraw-requests")
    public ApiResponse<PageResponse<WithdrawRequestResp>> withdrawRequests(
            @ModelAttribute WithdrawRequestSearchParam param) {
        return ApiResponse.ok(service.withdrawRequests(param));
    }

    @PostMapping("/withdraw-requests")
    public ApiResponse<Long> createWithdrawRequest(@Valid @RequestBody MobileWithdrawSaveReq req) {
        return ApiResponse.ok(service.createWithdrawRequest(req));
    }

    @PostMapping("/withdraw-requests/{requestId}/cancel")
    public ApiResponse<Void> cancelWithdrawRequest(@PathVariable Long requestId) {
        service.cancelMyWithdrawRequest(requestId);
        return ApiResponse.ok();
    }

    @PutMapping("/profile/phone")
    public ApiResponse<Void> updateMyPhone(@RequestBody PhoneReq req) {
        service.updateMyPhone(req.getPhone());
        return ApiResponse.ok();
    }

    @lombok.Data
    public static class PhoneReq {
        private String phone;
    }

    @GetMapping("/notifications")
    public ApiResponse<PageResponse<UserNotificationResp>> notifications(
            @ModelAttribute UserNotificationSearchParam param) {
        return ApiResponse.ok(service.notifications(param));
    }

    @PostMapping("/notifications/{notificationId}/read")
    public ApiResponse<Void> markRead(@PathVariable Long notificationId) {
        service.markNotificationRead(notificationId);
        return ApiResponse.ok();
    }

    @PostMapping("/notifications/read-all")
    public ApiResponse<Integer> markAllRead() {
        return ApiResponse.ok(service.markAllNotificationsRead());
    }

    /** 푸시용 디바이스 토큰 등록. body: {token, platform?} */
    @PostMapping("/device-tokens")
    public ApiResponse<Void> registerDeviceToken(@RequestBody java.util.Map<String, String> body) {
        service.registerDeviceToken(body.get("token"), body.get("platform"));
        return ApiResponse.ok();
    }

    /** 디바이스 토큰 해제(로그아웃 등). body: {token} */
    @PostMapping("/device-tokens/unregister")
    public ApiResponse<Void> unregisterDeviceToken(@RequestBody java.util.Map<String, String> body) {
        service.unregisterDeviceToken(body.get("token"));
        return ApiResponse.ok();
    }
}
