<?php

namespace App\Livewire\Forms\Studio\Information;

use App\Models\Broadcast;
use App\Traits\Media\WithMediaHandler;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Livewire\Form;

class BroadcastForm extends Form
{
    use WithMediaHandler;

    public ?Broadcast $broadcast = null;

    public string $title = '';

    public string $body = '';

    public ?string $link = null;

    public array $role_ids = [];

    public function rules(): array
    {
        return [
            'title' => ['required', 'string', 'max:30'],
            'body' => ['required', 'string', 'max:50'],
            'link' => ['nullable', 'url', 'max:50'],
            'role_ids' => ['required', 'array', 'min:1'],
            'role_ids.*' => Rule::exists('roles', 'id'),
        ];
    }

    public function validationAttributes(): array
    {
        return [
            'title' => 'judul',
            'link' => 'tautan',
            'role_ids' => 'audiensi',
            'role_ids.*' => 'audiensi',
        ];
    }

    public function setBroadcast(Broadcast $broadcast): void
    {
        $this->broadcast = $broadcast;

        $this->title = $broadcast->title;
        $this->body = $broadcast->body;
        $this->link = $broadcast->link;
        $this->role_ids = $broadcast->audiences->pluck('id')->toArray();
    }

    public function store(): array
    {
        $this->validate();

        DB::transaction(function () use (&$broadcast) {
            $broadcast = Broadcast::create([
                'user_id' => auth()->id(),
                'title' => $this->title,
                'body' => $this->body,
                'link' => $this->link,
            ]);

            $broadcast->audiences()->attach($this->role_ids);
        });

        return [
            'title' => $broadcast->title,
            'body' => $broadcast->body,
            'link' => $broadcast->link,
            'audience_ids' => $this->role_ids,
        ];
    }
}
