<?php

namespace App\Models;

use Database\Factories\AssistanceApplicationFactory;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Support\Carbon;

/**
 * @property int $id
 * @property int $user_id
 * @property string $status
 * @property Carbon|null $created_at
 * @property Carbon|null $updated_at
 * @property-read Collection<int, ApplicationAnswer> $answers
 * @property-read int|null $answers_count
 * @property-read Collection<int, AssistanceApplicationNote> $notes
 * @property-read int|null $notes_count
 * @property-read User $user
 *
 * @method static \Database\Factories\AssistanceApplicationFactory factory($count = null, $state = [])
 * @method static \Illuminate\Database\Eloquent\Builder<static>|AssistanceApplication newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder<static>|AssistanceApplication newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder<static>|AssistanceApplication query()
 * @method static \Illuminate\Database\Eloquent\Builder<static>|AssistanceApplication whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|AssistanceApplication whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|AssistanceApplication whereStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|AssistanceApplication whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|AssistanceApplication whereUserId($value)
 *
 * @mixin \Eloquent
 */
class AssistanceApplication extends Model
{
    /** @use HasFactory<AssistanceApplicationFactory> */
    use HasFactory;

    protected $fillable = [
        'user_id',
        'status',
    ];

    protected $attributes = [
        'status' => 'submitted',
    ];

    protected static function booted(): void
    {
        // application_answers is polymorphic with no DB foreign key cascade,
        // so clean up morph answers manually to avoid orphaned rows.
        static::deleting(function (AssistanceApplication $model): void {
            $model->answers()->delete();
        });
    }

    /**
     * @return BelongsTo<User, $this>
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * @return HasMany<AssistanceApplicationNote, $this>
     */
    public function notes(): HasMany
    {
        return $this->hasMany(AssistanceApplicationNote::class);
    }

    /**
     * @return MorphMany<ApplicationAnswer, $this>
     */
    public function answers(): MorphMany
    {
        return $this->morphMany(ApplicationAnswer::class, 'answerable')->orderBy('sort_order');
    }
}
