<?php

namespace App\Services\Application\FacadeServices;

use App\Models\Application\AI\FavoriteTemplate;
use App\Models\Application\AI\Template;
use App\Repositories\Core\Status\StatusRepository;
use App\Interfaces\TemplateInterface;
use App\Services\Core\BaseService;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;

class TemplateFacadeService extends BaseService implements TemplateInterface
{
    public function __construct(Template $template){
        $this->model = $template;
    }
    
    public function index()
    {
        return Template::with('category:id,name')
            ->where('status_id', resolve(StatusRepository::class)->templateActive())
            ->get()
            ->groupBy(function ($template) {
                return $template->category->name;
            });
    }

    public function store(array $request)
    {
        // TODO:
    }

    public function findBySlug(string $slug)
    {
        return Template::where('slug', $slug)->firstOrFail();
    }

    public function generatorData(): array
    {
        return [
            'ai_models' => config('settings.ai_models'),
            'tones' => config('settings.tones'),
            'creativities' => config('settings.creativities'),
            'languages' => config('language.languages'),
        ];
    }

    public function cachedTemplate()
    {
        if (Cache::get('template-cached-on') == date('Y-m-d')) {
            return Cache::get('cached-template');
        } else {
            return $this->storeCache();
        }
    }

    public function storeCache()
    {
        $templates = $this->index();

        $data = [];

        foreach ($templates->toArray() as $template) {
            foreach ($template as $item) {
                $data[$item['id']] = $item;
            }
        }

        Cache::put('cached-template', $data);
        Cache::put('template-cached-on', date('Y-m-d'));
        return $data;
    }
}
