<?php

namespace Ignite\Core\Entities;

use DateTimeInterface;
use Ignite\Core\Entities\Filters\QueryPermissionFilters;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

abstract class Base extends Model
{
    /**
     * The attributes which cannot be mass assigned.
     *
     * @var array
     */
    protected $guarded = [];

    /**
     * Prepare a date for array / JSON serialization.
     *
     * @param \DateTimeInterface $date
     * @return string
     */
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    /**
     * Filter this the query for this model down, so it only yields records that the given (or authed) user has for
     * the given permission.
     *
     * @param Builder $query
     * @param string $permission
     * @param User|null $user
     * @return void
     */
    public function scopeWhereHasPermission(Builder $query, string $permission, ?User $user = null)
    {
        $queryPermissionFilter = QueryPermissionFilters::for($permission);

        $queryPermissionFilter->assertForTable($this);

        // Not supporting aliasing of the table here. I guess we could add that as an argument, but not sure if that
        // would be used.
        $queryPermissionFilter->apply($query, null, $user);
    }
}
