<?php

namespace App\Services;

use App\Enums\DocumentTypeEnum;
use App\Exceptions\UploadFileException;
use App\Models\AttributeSiUnit;
use App\Models\Business;
use App\Models\Product;
use App\Models\SeasonEpisode;
use App\Models\Series;
use App\Models\SeriesSeason;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\UploadedFile;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

trait SeriesService
{
    /**
     * Store new record
     *
     * @param array $data
     * @return Builder|Model
     */
    public static function store(array $data): Model|Builder
    {
        return Series::query()->create($data);
    }

    /**
     * Update existing record
     *
     * @param array $data
     * @return mixed
     */
    public function updateService(array $data): mixed
    {
        return tap($this)->update($data);
    }

    /**
     * Find by id
     *
     * @param int $id
     * @return Builder|Builder[]|Collection|Model|null
     */
    public static function findById(int $id): Model|Collection|Builder|array|null
    {
        return Series::query()->find($id);
    }

    /**
     * Add new series
     *
     * @param UploadedFile $seriesPoster
     * @param Product $product
     * @param Business $business
     * @return Builder|Model
     * @throws UploadFileException
     */
    public static function createSeries(UploadedFile $seriesPoster, Product $product, Business $business): Model|Builder
    {
        $basePath = sprintf(
            config('torryme.paths.docs'),
            $business->buildProductDir($product->{'id'})
        );

        // Try to upload file ...
        $resultPath = upload_file_system(
            DocumentTypeEnum::seriesPoster->value,
            $basePath,
            $seriesPoster,
        );

        if(! filled($resultPath)) {
            throw new UploadFileException();
        }

        return Series::store(array(
            'cover' => $resultPath,
            'designation' => $product->{'designation'},
            'description' => $product->{'description'},
            'price' => $product->{'price'},
            'price_currency_id' => $product->{'price_currency_id'},
        ));
    }

    /**
     * Total number of episodes in the series
     *
     * @return int
     */
    public function totalEpisode(): int
    {
        return SeasonEpisode::totalSeriesEpisode($this);
    }

    /**
     * Total number of season in the series
     *
     * @return int
     */
    public function totalSeriesSeason(): int
    {
        return SeriesSeason::totalSeriesSeason($this);
    }
}
