<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Exception;

class SSOService
{
    /**
     * 使用 password grant_type 取得 access_token
     */
    public function getAccessTokenViaPasswordGrant(): string
    {
        $authHeader = base64_encode(
            config('sso.password_client_id') . ':' . config('sso.password_client_secret')
        );

        $response = Http::asForm()->withHeaders([
            'Authorization' => 'Basic ' . $authHeader,
        ])->post(config('sso.token_uri'), [
            'grant_type' => 'password',
            'username' => config('sso.password_username'),
            'password' => config('sso.password_password'),
        ]);

        if (!$response->successful()) {
            Log::error('SSO Password Grant Token Failed: ' . $response->body());
            throw new Exception('SSO Token 取得失敗');
        }

        return $response->json()['access_token'];
    }

    /**
     * 同步使用者資訊到IDA平台
     */
    public function syncUserToSSO(array $ssoPayload): void
    {
        $accessToken = $this->getAccessTokenViaPasswordGrant();

        $response = Http::withHeaders([
            'Accept' => 'application/json',
            'Authorization' => 'Bearer ' . $accessToken,
        ])->put(
            config('sso.base_url') . '/account/api/private/ida/kinghan/user/addOrUpdateUserWithSystemAuthority',
            $ssoPayload
        );

        Log::info('SSO 同步回應', [
            'status' => $response->status(),
            'body' => $response->body(),
        ]);

        if (!$response->successful()) {
            throw new Exception('SSO 同步失敗：' . $response->body());
        }
    }

    /**
     * 增加子系統登入紀錄回IDA
     */
    public function sendLoginLogToIDA(array $ssoPayload): void
    {
        $accessToken = $this->getAccessTokenViaPasswordGrant();

        Log::info('IDA 子系統登入紀錄 ssoPayload', $ssoPayload);

        $response = Http::withHeaders([
            'Accept' => 'application/json',
            'Authorization' => 'Bearer ' . $accessToken,
        ])->post(
            config('sso.base_url') . '/account/api/private/ida/kinghan/user/addLoginLog',
            $ssoPayload
        );

        Log::info('IDA 子系統登入紀錄', [
            'status' => $response->status(),
            'body' => $response->body(),
        ]);

        if (!$response->successful()) {
            throw new Exception('IDA 子系統登入紀錄失敗：' . $response->body());
        }
    }
}
