<?php

namespace App\Models;

use App\Models\Enums\ActionObjectType;
use App\Models\Enums\ContainerACL;
use App\Models\Scopes\CompanyScope;
use EloquentFilter\Filterable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;

class Container extends Model
{
    use HasFactory, SoftDeletes, Filterable;

    protected $fillable = [
        'name', 'library_id', 'naming_rule_id', 'naming_rules', 'mailto', 'email_subject', 'acl', 'whitelist',
        'doc_stage', 'doc_type'
    ];

    protected $casts = [
        'mailto' => 'array',
        'naming_rules' => 'array',
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s',
    ];

    protected static function booted(): void
    {
        static::addGlobalScope(new CompanyScope);
    }

    public function scopeAllowed(Builder $query, string $id = null)
    {
        $query->where(function (Builder $query) {
            return $query->where('acl', ContainerACL::PRIVATE->value)->where('created_by', Auth::id());
        })->orWhere(function (Builder $query) {
            return $query->where('acl', ContainerACL::CUSTOM->value)->where('whitelist', 'like', '%,' . Auth::id() . ',%');
        });
    }

    public function library(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(Library::class, "library_id");
    }

    public function namingRule(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(NamingRule::class);
    }

    public function createdBy(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function content(int $version = 0): \Illuminate\Database\Eloquent\Relations\HasOne
    {
        $version = $version > 0 ? $version : $this->version;

        return $this->hasOne(ContainerContent::class, "container_id")->where("version", $version);
    }

    public function folder()
    {
        return $this->hasMany(Folder::class, "object_id")->where("object_type", ActionObjectType::CONTAINER->value);
    }
}