<?php

namespace App\Http\Controllers\Api\Admin\Barobill;

use App\Http\Controllers\Controller;
use App\Models\Barobill\BarobillMember;
use App\Services\Barobill\BarobillService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class BarobillSmsController extends Controller
{
    public function __construct(
        protected BarobillService $barobillService
    ) {}

    /**
     * 회원사 조회 및 서버 모드 전환 헬퍼
     */
    private function resolveMember(): BarobillMember|JsonResponse
    {
        $tenantId = session('selected_tenant_id', 1);
        $member = BarobillMember::where('tenant_id', $tenantId)->first();

        if (! $member) {
            return response()->json([
                'success' => false,
                'message' => '바로빌 회원사가 등록되어 있지 않습니다.',
            ], 404);
        }

        $this->barobillService->setServerMode($member->server_mode ?? 'test');

        return $member;
    }

    /**
     * SMS 발송
     */
    public function sendSms(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'from_number' => 'required|string',
            'to_name' => 'required|string',
            'to_number' => 'required|string',
            'contents' => 'required|string',
            'send_dt' => 'nullable|string',
            'ref_key' => 'nullable|string',
        ]);

        $member = $this->resolveMember();
        if ($member instanceof JsonResponse) {
            return $member;
        }

        $result = $this->barobillService->sendSMSMessage(
            corpNum: $member->biz_no,
            senderId: $member->barobill_id,
            fromNumber: $validated['from_number'],
            toName: $validated['to_name'],
            toNumber: $validated['to_number'],
            contents: $validated['contents'],
            sendDT: $validated['send_dt'] ?? '',
            refKey: $validated['ref_key'] ?? ''
        );

        if (! $result['success']) {
            return response()->json($result, 422);
        }

        return response()->json($result);
    }

    /**
     * 등록된 발신번호 목록 조회
     */
    public function getFromNumbers(): JsonResponse
    {
        $member = $this->resolveMember();
        if ($member instanceof JsonResponse) {
            return $member;
        }

        $result = $this->barobillService->getSMSFromNumbers($member->biz_no);

        if (! $result['success']) {
            return response()->json($result, 422);
        }

        return response()->json($result);
    }

    /**
     * 발신번호 등록 여부 확인
     */
    public function checkFromNumber(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'from_number' => 'required|string',
        ]);

        $member = $this->resolveMember();
        if ($member instanceof JsonResponse) {
            return $member;
        }

        $result = $this->barobillService->checkSMSFromNumber(
            $member->biz_no,
            $validated['from_number']
        );

        if (! $result['success']) {
            return response()->json($result, 422);
        }

        return response()->json($result);
    }

    /**
     * SMS 전송 상태 조회
     */
    public function getSendState(string $sendKey): JsonResponse
    {
        $member = $this->resolveMember();
        if ($member instanceof JsonResponse) {
            return $member;
        }

        $result = $this->barobillService->getSMSSendState($member->biz_no, $sendKey);

        if (! $result['success']) {
            return response()->json($result, 422);
        }

        return response()->json($result);
    }
}
