<?php

namespace App\Http\Controllers;

use App\Http\Requests\ReleaseNoteRequest;
use App\Http\Requests\StoreReleaseNote;
use App\Http\Requests\UpdateReleaseNote;
use App\Http\Resources\ReleaseNoteList;
use App\Http\Resources\ReleaseNoteResource;
use App\Models\ReleaseNote;
use Illuminate\Support\Facades\Auth;

class ReleaseNoteController extends Controller
{
    public function index(ReleaseNoteRequest $request): ReleaseNoteList
    {
        return new ReleaseNoteList(ReleaseNote::query()->latest('published_at')->latest()->paginate());
    }

    public function show(ReleaseNoteRequest $request, ReleaseNote $releaseNote): ReleaseNoteResource
    {
        return new ReleaseNoteResource($releaseNote);
    }

    public function store(StoreReleaseNote $request): ReleaseNoteResource
    {
        $note = ReleaseNote::query()->create([
            'title' => $request->input('title'),
            'is_published' => false,
        ]);
        return new ReleaseNoteResource($note);
    }

    public function update(UpdateReleaseNote $request, ReleaseNote $releaseNote): ReleaseNoteResource
    {
        $releaseNote->update($request->validated());
        return new ReleaseNoteResource($releaseNote);
    }

    public function destroy(ReleaseNoteRequest $request, ReleaseNote $releaseNote): ReleaseNoteList
    {
        $releaseNote->delete();
        return $this->index($request);
    }

    public function viewList(): ReleaseNoteList
    {
        return new ReleaseNoteList(ReleaseNote::query()
            ->published()
            ->latest('published_at')
            ->latest()
            ->paginate()
            ->through(function (ReleaseNote $note) {
                $note->description = implode(' | ', array_filter([
                    !Auth::user()->hasSeenReleaseNote($note) ? '(NEW)' : '',
                    $note->published_at?->format('jS F Y'),

                ]));
                return $note;
            }));
    }
    public function view($noteId): ReleaseNoteResource
    {
        $releaseNote = ReleaseNote::query()->published()->find($noteId);
        Auth::user()->markSeenReleaseNote($releaseNote);
        $releaseNote->setHidden([
            'created_at',
            'updated_at',
            'is_published',
        ]);

        $releaseNote->publish_date = $releaseNote->published_at?->format('jS F Y');
        return new ReleaseNoteResource($releaseNote);
    }
}
