<?php

namespace App\Models;

use App\Enums\HuntDifficulty;
use App\Enums\HuntStatus;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Laravel\Scout\Searchable;

class Hunts extends Model
{
    use HasFactory;
    use Searchable;

    protected $table = 'hunts';

    protected $fillable = [
        'partner_id',
        'title',
        'slug',
        'description',
        'status',
        'difficulty',
        'city',
        'latitude',
        'longitude',
        'is_public',
        'estimated_duration_min',
        'start_at',
        'end_at',
        'image',
        'creator_id',
    ];

    protected $casts = [
        'is_public' => 'boolean',
        'start_at' => 'datetime',
        'end_at' => 'datetime',
        'latitude' => 'float',
        'longitude' => 'float',
        'estimated_duration_min' => 'integer',
        'status' => HuntStatus::class,
        'difficulty' => HuntDifficulty::class,
    ];

    public function steps(): HasMany
    {
        return $this->hasMany(HuntSteps::class, 'hunt_id');
    }

    public function participants(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'hunt_participants', 'hunt_id', 'user_id')
            ->withPivot(['current_step_number', 'status'])
            ->withTimestamps();
    }

    /**
     * @return array{
     *     id: int,
     *     title: string,
     *     slug: string,
     *     description: string|null,
     *     city: string,
     *     status: string,
     *     difficulty: string,
     *     is_public: bool,
     *     start_at: string|null,
     *     end_at: string|null
     * }
     */
    public function toSearchableArray(): array
    {
        $status = $this->status instanceof HuntStatus ? $this->status->value : $this->status;
        $difficulty = $this->difficulty instanceof HuntDifficulty ? $this->difficulty->value : $this->difficulty;

        return [
            'id' => $this->id,
            'title' => $this->title,
            'slug' => $this->slug,
            'description' => $this->description,
            'city' => $this->city,
            'status' => $status,
            'difficulty' => $difficulty,
            'is_public' => $this->is_public,
            'start_at' => $this->start_at?->toAtomString(),
            'end_at' => $this->end_at?->toAtomString(),
        ];
    }
}
