<?php

namespace App\Services\Admin\Stories;

use App\Models\Story;
use Illuminate\Http\Request;

class StoriesService
{
    /** get stories */
    public function getStories(Request $request)
    {
        $stories = Story::query()
            ->when($request->input('publish'), function ($query, $publish) {
                if ($publish) {
                    $query->where('status', 'publish');
                }
            })
            ->when($request->input('expired'), function ($query, $expired) {
                if ($expired) {
                    $query->where('status', 'expired');
                }
            })
            ->orderByRaw("FIELD(status , 'publish', 'expired') ASC")
            ->orderBy('created_at', 'desc')->get()->map(fn($story) => [
                'id' => $story->id,
                'type' => $story->type,
                'title' => $story->title,
                'cover' => $story->cover,
                'file' => $story->file,
                'widgets' => $story->widgets,
                'like' => $story->like,
                'status' => $story->status,
                'is_expired' => $story->is_expired,
                'jalali_expired_at' => $story->jalali_expired_at,
                'jalali_created_at' => $story->jalali_created_at,

                'user' => [
                    'id' => $story->user->id,
                    'get_name' => $story->user->get_name,
                    'username' => $story->user->username,
                ],
            ]);

        return $stories;
    }
}
