<?php

namespace App\Services;

use Laravel\Socialite\Two\AbstractProvider;
use Laravel\Socialite\Two\ProviderInterface;
use Laravel\Socialite\Two\User;

class EnvatoProvider extends AbstractProvider implements ProviderInterface
{
    /**
     * The base Envato URL.
     */
    protected string $baseUrl = 'https://api.envato.com';

    /**
     * Get the authentication URL for the provider.
     */
    protected function getAuthUrl($state): string
    {
        return $this->buildAuthUrlFromBase('https://api.envato.com/authorization', $state);
    }

    /**
     * Get the token URL for the provider.
     */
    protected function getTokenUrl(): string
    {
        return 'https://api.envato.com/token';
    }

    /**
     * Get the raw user for the given access token.
     */
    protected function getUserByToken($token): array
    {
        $response = $this->getHttpClient()->get($this->baseUrl.'/v1/market/private/user/account.json', [
            'headers' => [
                'Authorization' => 'Bearer '.$token,
            ],
        ]);

        $data = json_decode($response->getBody(), true);

        return $data;
    }

    /**
     * Map the raw user array to a Socialite User instance.
     */
    protected function mapUserToObject(array $user): User
    {
        $account = $user['account'] ?? [];

        // Generate a unique ID if not provided
        $id = $account['id'] ?? uniqid('envato_', true);

        // Generate username from firstname and surname if not provided
        $username = $account['username'] ?? strtolower(($account['firstname'] ?? 'user') . ($account['surname'] ?? ''));

        // For OAuth, we might not get email from this endpoint
        // We'll need to get it from somewhere else or generate one
        $email = $account['email'] ?? ($username . '@envato.temp');

        $name = trim(($account['firstname'] ?? '') . ' ' . ($account['surname'] ?? ''));


        return (new User)->setRaw($user)->map([
            'id' => $id,
            'nickname' => $username,
            'name' => $name,
            'email' => $email,
            'avatar' => $account['image'] ?? null,
        ]);
    }

    /**
     * Get the POST fields for the token request.
     */
    protected function getTokenFields($code): array
    {
        return array_merge(parent::getTokenFields($code), [
            'grant_type' => 'authorization_code',
        ]);
    }
}