<?php

declare(strict_types=1);

namespace App\Services\Identity;

use Illuminate\Support\Str;

class NiceProvider implements IdentityProviderInterface
{
    public function __construct(private readonly array $config = [])
    {
    }

    public function provider(): string
    {
        return 'nice';
    }

    public function isMock(): bool
    {
        return (bool) ($this->config['mock'] ?? false);
    }

    public function buildRequest(array $context = []): array
    {
        $requestId = 'NICE-'.Str::ulid()->toString();
        if ($this->isMock()) {
            return [
                'request_id' => $requestId,
                'standard_url' => url('/api/v1/identity/mock-window?request_id='.$requestId.'&provider=nice'),
                'mock' => true,
            ];
        }
        // Real NICE: encrypt + sign request via Java/PHP module; return their standard URL.
        return [
            'request_id' => $requestId,
            'standard_url' => 'https://nice.checkplus.co.kr/CheckPlusSafeModel/checkplus.cb',
        ];
    }

    public function parseCallback(array $payload): array
    {
        if ($this->isMock()) {
            return [
                'status' => 'verified',
                'ci' => 'MOCK-CI-'.hash('sha256', json_encode($payload).$payload['request_id'] ?? ''),
                'di' => 'MOCK-DI-'.hash('sha256', $payload['request_id'] ?? Str::random(16)),
                'name' => $payload['name'] ?? '홍길동',
                'birthdate' => $payload['birthdate'] ?? '1990-01-01',
                'gender' => $payload['gender'] ?? 'male',
                'mobile' => $payload['mobile'] ?? '01012345678',
                'carrier' => $payload['carrier'] ?? 'skt',
                'raw' => array_merge(['mock' => true], $payload),
            ];
        }
        return [
            'status' => $payload['result'] ?? 'failed',
            'ci' => $payload['ci'] ?? null,
            'di' => $payload['di'] ?? null,
            'name' => $payload['name'] ?? null,
            'birthdate' => $payload['birthdate'] ?? null,
            'gender' => $payload['gender'] ?? null,
            'mobile' => $payload['mobile'] ?? null,
            'carrier' => $payload['carrier'] ?? null,
            'raw' => $payload,
        ];
    }
}
