<?php

namespace App\Http\Controllers\Api\V1;

use App\Helpers\ApiResponse;
use App\Http\Controllers\Controller;
use App\Services\ReceivablesService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * 채권 현황 컨트롤러
 */
class ReceivablesController extends Controller
{
    public function __construct(
        protected ReceivablesService $service
    ) {}

    /**
     * 채권 현황 목록 조회
     */
    public function index(Request $request): JsonResponse
    {
        return ApiResponse::handle(function () use ($request) {
            $params = $request->validate([
                'year' => 'nullable|integer|min:2000|max:2100', 'recent_year' => 'nullable|string|in:true,false,1,0',
                'search' => 'nullable|string|max:100',
                'has_receivable' => 'nullable|string|in:true,false,1,0',
            ]);

            // 문자열 boolean을 실제 boolean으로 변환
            if (isset($params['recent_year'])) {
                $params['recent_year'] = filter_var($params['recent_year'], FILTER_VALIDATE_BOOLEAN);
            }
            if (isset($params['has_receivable'])) {
                $params['has_receivable'] = filter_var($params['has_receivable'], FILTER_VALIDATE_BOOLEAN);
            }

            \Log::info('[Receivables] index params', $params);

            return $this->service->index($params);
        }, __('message.fetched'));
    }

    /**
     * 채권 현황 요약 통계
     */
    public function summary(Request $request): JsonResponse
    {
        return ApiResponse::handle(function () use ($request) {
            $params = $request->validate([
                'year' => 'nullable|integer|min:2000|max:2100',
                'recent_year' => 'nullable|string|in:true,false,1,0',
            ]);

            // 문자열 boolean을 실제 boolean으로 변환
            if (isset($params['recent_year'])) {
                $params['recent_year'] = filter_var($params['recent_year'], FILTER_VALIDATE_BOOLEAN);
            }

            \Log::info('[Receivables] summary params', $params);

            return $this->service->summary($params);
        }, __('message.fetched'));
    }

    /**
     * 연체 상태 일괄 업데이트
     */
    public function updateOverdueStatus(Request $request): JsonResponse
    {
        return ApiResponse::handle(function () use ($request) {
            $validated = $request->validate([
                'updates' => 'required|array|min:1',
                'updates.*.id' => 'required|integer|exists:clients,id',
                'updates.*.is_overdue' => 'required|boolean',
            ]);

            $updatedCount = $this->service->updateOverdueStatus($validated['updates']);

            return ['updated_count' => $updatedCount];
        }, __('message.updated'));
    }

    /**
     * 거래처 메모 일괄 업데이트
     */
    public function updateMemos(Request $request): JsonResponse
    {
        return ApiResponse::handle(function () use ($request) {
            $validated = $request->validate([
                'memos' => 'required|array|min:1',
                'memos.*.id' => 'required|integer|exists:clients,id',
                'memos.*.memo' => 'nullable|string|max:1000',
            ]);

            $updatedCount = $this->service->updateMemos($validated['memos']);

            return ['updated_count' => $updatedCount];
        }, __('message.updated'));
    }
}
