<?php

namespace App\Actions;

use App\Enums\AccountStatusEnum;
use App\Exceptions\PlatformAuthException;
use App\Models\PlatformAccount;
use App\Models\PlatformInstance;
use App\Services\Auth\LemmyAuthService;
use Illuminate\Support\Facades\DB;

class CreatePlatformAccountAction
{
    public function __construct(
        private readonly LemmyAuthService $lemmyAuthService,
    ) {}

    /**
     * @throws PlatformAuthException
     */
    public function execute(string $instanceDomain, string $username, string $password, string $platform = 'lemmy'): PlatformAccount
    {
        $fullInstanceUrl = 'https://'.$instanceDomain;

        // Authenticate first — if this fails, no records are created
        $authResponse = $this->lemmyAuthService->authenticate($fullInstanceUrl, $username, $password);

        return DB::transaction(function () use ($fullInstanceUrl, $instanceDomain, $username, $password, $platform, $authResponse) {
            $platformInstance = PlatformInstance::firstOrCreate([
                'url' => $fullInstanceUrl,
                'platform' => $platform,
            ], [
                'name' => ucfirst($instanceDomain),
                'is_active' => true,
            ]);

            return PlatformAccount::create([
                'platform' => $platform,
                'instance_url' => $fullInstanceUrl,
                'username' => $username,
                'password' => $password,
                'settings' => [
                    'display_name' => $authResponse['person_view']['person']['display_name'] ?? null,
                    'description' => $authResponse['person_view']['person']['bio'] ?? null,
                    'person_id' => $authResponse['person_view']['person']['id'] ?? null,
                    'platform_instance_id' => $platformInstance->id,
                    'api_token' => $authResponse['jwt'] ?? null,
                ],
                'is_active' => true,
                'status' => AccountStatusEnum::HEALTHY,
            ]);
        });
    }
}
