<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Http\Client\Response;

class AuthApiClient
{
    protected string $loginUrl;

    public function __construct()
    {
        $this->loginUrl = (string) config('services.auth_api.login_url');
    }

    public function login(string $email, string $password): array
    {
        $response = Http::asJson()->post($this->loginUrl, [
            'email' => $email,
            'password' => $password,
        ]);

        if (! $response->ok()) {
            return [
                'ok' => false,
                'message' => $this->extractError($response),
                'status' => $response->status(),
            ];
        }

        $json = $response->json() ?? [];

        // New: support accessToken/refreshToken while keeping old keys
        $accessToken = $json['accessToken']
            ?? $json['access_token']
            ?? $json['token']
            ?? ($json['data']['token'] ?? null);

        $refreshToken = $json['refreshToken']
            ?? $json['refresh_token']
            ?? ($json['data']['refresh_token'] ?? null);

        if (! $accessToken) {
            return [
                'ok' => false,
                'message' => 'Token tidak ditemukan pada respons API.',
                'status' => $response->status(),
                'raw' => $json,
            ];
        }

        return [
            'ok' => true,
            'token' => $accessToken,
            'refresh_token' => $refreshToken,
            'user' => $json['user'] ?? ($json['data']['user'] ?? null),
            'raw' => $json,
        ];
    }

    protected function extractError(Response $response): string
    {
        $json = $response->json();
        if (is_array($json)) {
            return $json['message'] ?? $json['error'] ?? 'Login gagal ke API.';
        }
        return 'Login gagal ke API.';
    }
}
