<?php

namespace App\Livewire\Forms\Studio\Manage;

use App\Enums\ArticleStatus;
use App\Models\Article;
use App\Traits\WithMediaHandler;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Livewire\Form;

class ArticleForm extends Form
{
    use WithMediaHandler;

    public ?Article $article = null;

    public string $title = '';

    public string $excerpt = '';

    public string $content = '';

    public string $status = '1';

    public array $thumbnail = [];

    public function rules(): array
    {
        return [
            'title' => ['required', 'string', 'max:200'],
            'excerpt' => ['required', 'string'],
            'content' => ['required', 'string'],
            'status' => ['required', Rule::in(ArticleStatus::cases())],
            'thumbnail' => ['required', 'array'],
        ];
    }

    public function validationAttributes(): array
    {
        return [
            'title' => 'judul',
            'excerpt' => 'cuplikan',
            'content' => 'konten',
        ];
    }

    public function setArticle(Article $article)
    {
        $this->article = $article;

        $this->title = $article->title;
        $this->excerpt = $article->excerpt;
        $this->content = $article->content;
        $this->status = $article->status->value;
        $this->thumbnail = $this->mapMediaCollection($article->getMedia('thumbnail'));
    }

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

        DB::transaction(function () {
            $article = Article::create([
                'author_id' => auth()->id(),
                'title' => $this->title,
                'excerpt' => $this->excerpt,
                'content' => $this->content,
                'status' => $this->status,
                'published_at' => $this->status == ArticleStatus::PUBLISHED->value ? now() : null,
            ]);

            $this->uploadMedia($this->thumbnail, $article, 'thumbnail');
        });
    }

    public function update()
    {
        $this->validate();

        DB::transaction(function () {
            $this->article->update(array_merge(
                [
                    'title' => $this->title,
                    'excerpt' => $this->excerpt,
                    'content' => $this->content,
                    'status' => $this->status,
                ],
                ($this->status == ArticleStatus::PUBLISHED->value && ! $this->article->published_at)
                    ? ['published_at' => now()]
                    : []
            ));

            $this->syncMedia($this->thumbnail, $this->article, 'thumbnail');
            $this->uploadMedia($this->thumbnail, $this->article, 'thumbnail');
        });
    }
}
