<?php

namespace App\Modules\Lemmy\Services;

use App\Exceptions\PlatformAuthException;
use App\Models\Article;
use App\Models\PlatformAccount;
use App\Models\PlatformChannel;
use App\Services\Auth\LemmyAuthService;
use Exception;

class LemmyPublisher
{
    private LemmyApiService $api;

    private PlatformAccount $account;

    public function __construct(PlatformAccount $account)
    {
        $this->api = new LemmyApiService($account->instance_url);
        $this->account = $account;
    }

    /**
     * @param  array<string, mixed>  $extractedData
     * @return array<string, mixed>
     *
     * @throws PlatformAuthException
     * @throws Exception
     */
    public function publishToChannel(Article $article, array $extractedData, PlatformChannel $channel): array
    {
        $authService = resolve(LemmyAuthService::class);
        $token = $authService->getToken($this->account);

        try {
            return $this->createPost($token, $extractedData, $channel, $article);
        } catch (Exception $e) {
            // If the cached token was stale, refresh and retry once
            if (str_contains($e->getMessage(), 'not_logged_in') || str_contains($e->getMessage(), 'Unauthorized')) {
                $token = $authService->refreshToken($this->account);

                return $this->createPost($token, $extractedData, $channel, $article);
            }
            throw $e;
        }
    }

    /**
     * @param  array<string, mixed>  $extractedData
     * @return array<string, mixed>
     */
    private function createPost(string $token, array $extractedData, PlatformChannel $channel, Article $article): array
    {
        $languageId = $extractedData['language_id'] ?? null;

        return $this->api->createPost(
            $token,
            $extractedData['title'] ?? 'Untitled',
            $extractedData['description'] ?? '',
            $channel->channel_id,
            $article->url,
            $extractedData['thumbnail'] ?? null,
            $languageId
        );
    }
}
