<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class PayjpThreeDSecureService
{
    private const API_BASE = 'https://api.pay.jp/v1';

    public function createRequest(string $payjpCardId): array
    {
        $response = Http::withBasicAuth(config('payjp.secret_key'), '')
            ->asForm()
            ->post(self::API_BASE . '/three_d_secure_requests', [
                'resource_id' => $payjpCardId,
            ]);

        if (!$response->successful()) {
            \Illuminate\Support\Facades\Log::warning('PAY.JP 3DS createRequest failed', [
                'status' => $response->status(),
                'body' => $response->body(),
                'card_id' => $payjpCardId,
            ]);
            throw new \RuntimeException('PAY.JP 3Dセキュアリクエストの作成に失敗しました: ' . $response->body());
        }

        return $response->json();
    }

    public function retrieveRequest(string $requestId): array
    {
        $response = Http::withBasicAuth(config('payjp.secret_key'), '')
            ->get(self::API_BASE . '/three_d_secure_requests/' . $requestId);

        if (!$response->successful()) {
            throw new \RuntimeException('PAY.JP 3Dセキュア結果の取得に失敗しました。');
        }

        return $response->json();
    }

    public function isSuccessful(array $threeDSecureRequest): bool
    {
        return ($threeDSecureRequest['state'] ?? null) === 'finished'
            && in_array($threeDSecureRequest['three_d_secure_status'] ?? null, ['verified', 'attempted'], true);
    }
}
