<?php

namespace App\Models;

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\HasOne;

class Mission extends Model
{
    use HasFactory;

    protected $fillable = [
        'client_id',
        'liner_id',
        'title',
        'description',
        'event_name',
        'location',
        'expected_start_at',
        'status',
        'budget_amount',
        'currency',
        'accepted_at',
        'client_validated_at',
        'started_at',
        'arrived_at',
        'completed_at',
        'cancelled_at',
    ];

    protected function casts(): array
    {
        return [
            'expected_start_at' => 'datetime',
            'accepted_at' => 'datetime',
            'client_validated_at' => 'datetime',
            'started_at' => 'datetime',
            'arrived_at' => 'datetime',
            'completed_at' => 'datetime',
            'cancelled_at' => 'datetime',
            'budget_amount' => 'decimal:2',
        ];
    }

    public function client(): BelongsTo
    {
        return $this->belongsTo(User::class, 'client_id');
    }

    public function liner(): BelongsTo
    {
        return $this->belongsTo(User::class, 'liner_id');
    }

    public function statusEvents(): HasMany
    {
        return $this->hasMany(MissionStatusEvent::class);
    }

    public function latestLocationEvent(): HasOne
    {
        return $this->hasOne(MissionStatusEvent::class)
            ->whereNotNull('latitude')
            ->whereNotNull('longitude')
            ->latestOfMany();
    }

    public function proofs(): HasMany
    {
        return $this->hasMany(MissionProof::class);
    }
    public function pendingLiner()
    {
    return $this->belongsTo(User::class, 'pending_liner_id');
    }
    public function messages(): HasMany
    {
        return $this->hasMany(MissionMessage::class);
    }

    public function applications(): HasMany
    {
        return $this->hasMany(MissionApplication::class);
    }

    public function disputes(): HasMany
    {
        return $this->hasMany(MissionDispute::class);
    }
}
