<?php

namespace App\Models;

use App\Http\Controllers\Api\Platform\StorageFileController;
use App\Services\SeriesService;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Series extends Model
{
    use HasFactory, SoftDeletes;
    use SeriesService;

    static string $prefixDir = "series_";

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'series';

    /**
     * Attributes that should be mass-assignable.
     *
     * @var array
     */
    protected $fillable = [
        'designation',
        'description',
        'cover',
        'price',

        'price_currency_id',
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'price_currency_id'
    ];

    /**
     * The attributes that should be casted to native types.
     *
     * @var array
     */
    protected $casts = [];

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['created_at', 'updated_at', 'deleted_at'];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['last_season_occurrence', 'cover_url'];

    /**
     * The "booting" method of the model.
     *
     * @return void
     */
    public static function boot(): void
    {
        parent::boot();
    }

    /**  Append attributes */

    public function getLastSeasonOccurrenceAttribute(): ?string
    {
        $season = $this->seasons()->orderByDesc('occurrence')->first();

        return $season !== null ? $season->{'occurrence'} : 1;
    }

    public function getCoverUrlAttribute(): ?string
    {
        if (filled($this->{'cover'})) {
            return route('serve.doc', [
                'resourceId' => $this->{'id'},
                'q' => StorageFileController::seriesCover,
                'file' => $this->{'cover'}
            ]);
        }

        return null;
    }

    /** Attributes used outside the class to create modify the resource */

    /**
     * Build cover or series file dir path
     *
     * @param string $path
     * @return string
     */
    public function buildSeriesFilePath(string $path): string
    {
        $product = $this->{'product'};
        $ownerUserId = $product->{'business'}->{'owner_user_id'};
        $productId = $product->{'id'};

        return sprintf(
            config('torryme.paths.docs'),
            sprintf(
                '%s%s/%s%s/%s%s/%s',
                User::$prefixDir, $ownerUserId,
                Business::$prefixDir, $product->{'business_id'},
                Product::$prefixDir, $productId,
                $path
            )
        );
    }

    /**
     * Get movie file size
     *
     * @return int
     */
    public function getTotalSize(): int
    {
        $totalSize = 0;
        $seasons = $this->{'seasons'};

        foreach ($seasons as $season) {
            $totalSize = $totalSize + $season->totalSize();
        }

        return $totalSize;
    }

    /** Relations */

    public function seasons(): \Illuminate\Database\Eloquent\Relations\HasMany
    {
        return $this->hasMany(SeriesSeason::class, "series_id");
    }

    public function product(): \Illuminate\Database\Eloquent\Relations\HasOne
    {
        return $this->hasOne(Product::class);
    }

    public function currency(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(Currency::class, "price_currency_id");
    }
}
