<?php

declare(strict_types=1);

namespace App\Models\Admin;

use App\Events\Admin\Announcement\AnnouncementCreated;
use App\Events\Admin\Announcement\AnnouncementDeleted;
use App\Events\Admin\Announcement\AnnouncementUpdated;
use App\Models\BaseModel;
use Database\Factories\Admin\AnnouncementFactory;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Date;
use OwenIt\Auditing\Auditable as HasAudits;
use OwenIt\Auditing\Contracts\Auditable;

/**
 * @property int $announcement_id
 * @property string $content
 * @property Carbon $end_at
 * @property Carbon $start_at
 *
 * @method static AnnouncementFactory factory(...$parameters)
 * @method static Builder<static> current()
 */
#[Table(Announcement::TABLE, Announcement::ATTRIBUTE_ID)]
class Announcement extends BaseModel implements Auditable
{
    use HasAudits;
    use HasFactory;

    final public const string TABLE = 'announcements';

    final public const string ATTRIBUTE_CONTENT = 'content';
    final public const string ATTRIBUTE_END_AT = 'end_at';
    final public const string ATTRIBUTE_ID = 'announcement_id';
    final public const string ATTRIBUTE_START_AT = 'start_at';

    /**
     * The event map for the model.
     *
     * Allows for object-based events for native Eloquent events.
     *
     * @var array<string, class-string>
     */
    protected $dispatchesEvents = [
        'created' => AnnouncementCreated::class,
        'deleted' => AnnouncementDeleted::class,
        'updated' => AnnouncementUpdated::class,
    ];

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        Announcement::ATTRIBUTE_CONTENT,
        Announcement::ATTRIBUTE_END_AT,
        Announcement::ATTRIBUTE_START_AT,
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            Announcement::ATTRIBUTE_CONTENT => 'string',
            Announcement::ATTRIBUTE_END_AT => 'datetime',
            Announcement::ATTRIBUTE_START_AT => 'datetime',
        ];
    }

    public function getName(): string
    {
        return strval($this->getKey());
    }

    public function getSubtitle(): string
    {
        return $this->getName();
    }

    /**
     * Scope a query to only include current announcements.
     */
    #[Scope]
    protected function current(Builder $query): void
    {
        $query->whereValueBetween(Date::now(), [
            Announcement::ATTRIBUTE_START_AT,
            Announcement::ATTRIBUTE_END_AT,
        ]);
    }
}
