<?php

namespace App\Carriers\Models;

use App\Bookings\Models\Booking;
use App\Equipment\Models\Equipment;
use App\Shared\Contracts\Tenancy;
use App\Shared\Models\Traits\HasClient;
use App\Shared\Models\Traits\HasTenancy;
use Awobaz\Compoships\Compoships;
use Awobaz\Compoships\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class ClientCarrier extends Model implements Tenancy
{
    use SoftDeletes;
    use HasTenancy;
    use HasClient;
    use Compoships;

    protected $connection = 'newtrul';

    protected $fillable = [
        'carrier_id',
        'client_id',
        'external_id',
        'is_disqualified',
        'active',
        'name',
        'legal_name',
        'address_line_1',
        'city',
        'state',
        'postal_code',
        'email',
    ];

    protected $appends = ['dot_number', 'mc_number'];

    public function carrier(): BelongsTo
    {
        return $this->belongsTo(Carrier::class);
    }

    public function equipment(): HasMany
    {
        return $this->hasMany(ClientCarrierEquipment::class, ['carrier_id','client_id'], ['id','client_id']);
    }

    public function contacts(): HasMany
    {
        return $this->hasMany(ClientCarrierContact::class, 'carrier_id', 'id');
    }

    public function bookings(): HasMany
    {
        return $this->hasMany(Booking::class, 'carrier_id', 'id')
            ->where('client_id', $this->client_id);
    }

    public function equipmentTypes(): Attribute
    {
        return new Attribute(get: fn() => Equipment::whereIn('id', $this->equipment->pluck('equipment_id'))->get());
    }

    public function equipmentTotal(): Attribute
    {
        return new Attribute(get: fn() => $this->equipment->sum('quantity'));
    }

    public function dotNumber(): Attribute
    {
        return new Attribute(get: fn() => $this->carrier->dot_number);
    }

    public function mcNumber(): Attribute
    {
        return new Attribute(get: fn() => $this->carrier->mc_number);
    }

    public function preferredLanes()
    {
        return $this->hasMany(ClientCarrierPreferredLane::class, 'client_carrier_id');
    }

    public function availableTrucks(): HasMany
    {
        return $this->hasMany(ClientCarrierAvailableTrucks::class, 'client_carrier_id', 'id');
    }

}