<?php

namespace App\Models;

use App\Enums\ClientStatus;
use App\Enums\LegalForm;
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;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\LogsActivity;

class Client extends Model
{
    /** @use HasFactory<\Database\Factories\ClientFactory> */
    use HasFactory, LogsActivity, SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'workspace_id',
        'company_name',
        'legal_form',
        'ice',
        'fiscal_id',
        'rc',
        'cnss',
        'patente',
        'contact_last_name',
        'contact_first_name',
        'contact_job_title',
        'contact_email',
        'contact_phone',
        'internal_responsible_id',
        'status',
        'internal_notes',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'legal_form' => LegalForm::class,
            'status' => ClientStatus::class,
        ];
    }

    /**
     * Get the workspace that owns the client.
     *
     * @return BelongsTo<Workspace, $this>
     */
    public function workspace(): BelongsTo
    {
        return $this->belongsTo(Workspace::class);
    }

    /**
     * Get the internal responsible user.
     *
     * @return BelongsTo<User, $this>
     */
    public function internalResponsible(): BelongsTo
    {
        return $this->belongsTo(User::class, 'internal_responsible_id');
    }

    /**
     * Get the contacts for the client.
     *
     * @return HasMany<ClientContact>
     */
    public function contacts(): HasMany
    {
        return $this->hasMany(ClientContact::class);
    }

    /**
     * Get the primary contact for the client.
     *
     * @return HasOne<ClientContact>
     */
    public function primaryContact(): HasOne
    {
        return $this->hasOne(ClientContact::class)->where('is_principal', true)->latest();
    }

    public function getPrimaryContactEmailAttribute(): ?string
    {
        return $this->primaryContact?->email ?? $this->contact_email;
    }

    /**
     * Get the declarations for the client.
     *
     * @return HasMany<Declaration>
     */
    public function declarations(): HasMany
    {
        return $this->hasMany(Declaration::class);
    }

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logFillable()
            ->logOnlyDirty()
            ->dontSubmitEmptyLogs();
    }
}
