<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class VesselCrew extends Model
{
    use HasFactory;

    protected $table = 'vessel_crews';

    protected $fillable = [
        'vessel_id',
        'fisherman_id',
        'role',
        'is_primary',
        'joined_at',
        'left_at',
        'notes',
    ];

    protected $casts = [
        'joined_at' => 'date',
        'left_at' => 'date',
        'is_primary' => 'boolean',
    ];

    // Role constants
    const ROLE_CAPTAIN = 'captain';
    const ROLE_ENGINEER = 'engineer';
    const ROLE_NAVIGATOR = 'navigator';
    const ROLE_FISHERMAN = 'fisherman';
    const ROLE_COOK = 'cook';
    const ROLE_OTHER = 'other';

    const ROLE_LIST = [
        self::ROLE_CAPTAIN => 'Capitão',
        self::ROLE_ENGINEER => 'Engenheiro',
        self::ROLE_NAVIGATOR => 'Navegador',
        self::ROLE_FISHERMAN => 'Pescador',
        self::ROLE_COOK => 'Cozinheiro',
        self::ROLE_OTHER => 'Outro',
    ];

    // Relationships
    public function vessel()
    {
        return $this->belongsTo(Vessel::class);
    }

    public function fisherman()
    {
        return $this->belongsTo(Fisherman::class);
    }

    // Scopes
    public function scopeActive($query)
    {
        return $query->whereNull('left_at');
    }

    public function scopePrimary($query)
    {
        return $query->where('is_primary', true);
    }

    // Accessors
    public function getRoleTextAttribute()
    {
        return self::ROLE_LIST[$this->role] ?? $this->role;
    }

    public function getIsActiveAttribute()
    {
        return is_null($this->left_at);
    }

    public function getJoinedAtFormattedAttribute()
    {
        return $this->joined_at ? $this->joined_at->format('d/m/Y') : '-';
    }

    public function getLeftAtFormattedAttribute()
    {
        return $this->left_at ? $this->left_at->format('d/m/Y') : '-';
    }

    // Methods
    public function dismiss($leftAt = null, $reason = null)
    {
        $this->update([
            'left_at' => $leftAt ?? now(),
            'notes' => $reason ?? $this->notes,
        ]);
    }

    public function promoteToCaptain()
    {
        $this->update(['role' => self::ROLE_CAPTAIN]);
    }

    public function makePrimary()
    {
        // Remove primary status from other crew members
        $this->vessel->crews()->active()->update(['is_primary' => false]);
        $this->update(['is_primary' => true]);
    }
}
