<?php

declare(strict_types=1);

namespace Maestro\Core\Modules\Customers\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Maestro\Core\Support\AuthUserResolver;

/**
 * CRM customer record for this deployment (single database = single instance).
 */
class Customer extends Model
{
    use SoftDeletes;

    /**
     * @var list<string>
     */
    protected $fillable = [
        'name',
        'email',
        'phone',
        'website',
        'notes',
        'is_active',
        'project_manager_id',
    ];

    /**
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'is_active' => 'boolean',
        ];
    }

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

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

    /** Hour-registration approver for lines booked on this customer. */
    public function projectManager(): BelongsTo
    {
        return $this->belongsTo(AuthUserResolver::eloquentModelClass(), 'project_manager_id');
    }

    /**
     * @param  Builder<Customer>  $query
     * @return Builder<Customer>
     */
    public function scopeActive(Builder $query): Builder
    {
        return $query->where('is_active', true);
    }
}
