<?php

namespace App\Actions;

use App\Models\PlatformAccount;
use App\Models\PlatformChannel;
use App\Models\PlatformInstance;
use Illuminate\Support\Facades\DB;
use RuntimeException;

class CreateChannelAction
{
    public function execute(string $name, int $communityId, int $platformInstanceId, ?int $languageId = null, ?string $description = null): PlatformChannel
    {
        $platformInstance = PlatformInstance::findOrFail($platformInstanceId);

        $activeAccounts = PlatformAccount::where('instance_url', $platformInstance->url)
            ->where('is_active', true)
            ->get();

        if ($activeAccounts->isEmpty()) {
            throw new RuntimeException('No active platform accounts found for this instance. Please create a platform account first.');
        }

        return DB::transaction(function () use ($name, $communityId, $platformInstanceId, $languageId, $description, $activeAccounts) {
            $channel = PlatformChannel::create([
                'platform_instance_id' => $platformInstanceId,
                'channel_id' => $communityId,
                'name' => $name,
                'display_name' => ucfirst($name),
                'description' => $description,
                'language_id' => $languageId,
                'is_active' => true,
            ]);

            // Attach only the first active account — additional accounts can be linked via the channel management UI
            $channel->platformAccounts()->attach($activeAccounts->first()->id, [
                'is_active' => true,
                'priority' => 1,
                'created_at' => now(),
                'updated_at' => now(),
            ]);

            return $channel->load('platformAccounts');
        });
    }
}
