<?php

namespace App\Services;

use App\Models\Customer;
use Illuminate\Support\Facades\Log;
use App\Services\Contracts\AikDigitalClientInterface;


/**
 * Handles UUID-based customer lookup and onboarding (Section 2–4 of spec).
 */
class CustomerService
{
    // public function __construct(
    //     private AikDigitalApiClient $apiClient
    // ) {}

    public function __construct(private AikDigitalClientInterface $apiClient) {}


    /**
     * Resolve a customer from a UUID.
     *
     * Spec logic (Section 2.3):
     *  - UUID missing/empty  → error
     *  - UUID in EFUL DB     → return existing record
     *  - UUID not in EFUL DB → call inquireUserInfo, create record, return it
     *
     * @throws \InvalidArgumentException if UUID is missing
     * @throws \RuntimeException         if AIK Digital returns a non-S status
     */
    public function resolveCustomer(string $uuid): Customer
    {
        if (empty(trim($uuid))) {
            throw new \InvalidArgumentException('UUID is missing or empty.');
        }

        if (!$this->isValidUuidV4($uuid)) {
            throw new \InvalidArgumentException('UUID format is invalid: ' . $uuid);
        }

        // Check existing record
        $customer = Customer::where('open_id', $uuid)->first();
        if ($customer) {
            Log::info("CustomerService: returning customer UUID={$uuid}");
            return $customer;
        }

        // New customer → call AIK Digital
        Log::info("CustomerService: new customer, calling inquireUserInfo UUID={$uuid}");
        $response = $this->apiClient->inquireUserInfo($uuid);

        $status = $response['result']['resultStatus'] ?? 'U';

        if ($status === 'F') {
            throw new \RuntimeException(
                'inquireUserInfo failed: ' . ($response['result']['resultCode'] ?? 'UNKNOWN')
                . ' — ' . ($response['result']['resultMessage'] ?? '')
            );
        }

        if ($status === 'U') {
            throw new \RuntimeException('inquireUserInfo returned UNKNOWN status — please retry.');
        }

        $info = $response['userInfo'];

        $customer = Customer::create([
            'open_id'  => $info['openId'],
            'union_id' => $info['unionId']  ?? null,
            'msisdn'   => $info['userMsisdn'],
            'name'     => $info['userName'],
            'email'    => $info['Email']    ?? null,
            'dob'      => $info['Dob']      ?? null,
            'cnic'     => $info['CNIC']     ?? null,
            'gender'   => $info['Gender']   ?? null,
        ]);

        Log::info("CustomerService: created new customer ID={$customer->id} UUID={$uuid}");

        return $customer;
    }

    private function isValidUuidV4(string $uuid): bool
    {
        return (bool) preg_match(
            '/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i',
            $uuid
        );
    }
}
