<?php

namespace App\Actions;

use App\Models\Feed;
use App\Models\Language;
use InvalidArgumentException;

class CreateFeedAction
{
    public function execute(string $name, string $provider, int $languageId, ?string $description = null): Feed
    {
        $language = Language::findOrFail($languageId);
        $langCode = $language->short_code;

        $url = config("feed.providers.{$provider}.languages.{$langCode}.url");

        if (! $url) {
            throw new InvalidArgumentException("Invalid provider and language combination: {$provider}/{$langCode}");
        }

        $providerConfig = config("feed.providers.{$provider}");

        return Feed::firstOrCreate(
            ['url' => $url],
            [
                'name' => $name,
                'type' => $providerConfig['type'] ?? 'website',
                'provider' => $provider,
                'language_id' => $languageId,
                'description' => $description,
                'is_active' => true,
            ]
        );
    }
}
