<?php

declare(strict_types=1);

namespace ImovelZapAi\Owners\Infrastructure\Persistence\Eloquent;

use App\Models\User;
use Database\Factories\OwnerFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use ImovelZapAi\Owners\Domain\Enums\OwnerContactChannel;
use ImovelZapAi\Owners\Domain\Enums\OwnerType;
use ImovelZapAi\Properties\Infrastructure\Persistence\Eloquent\PropertyModel;
use ImovelZapAi\Shared\Infrastructure\Persistence\Concerns\BelongsToTenant;
use ImovelZapAi\Shared\Infrastructure\Persistence\Concerns\HasUuidPrimaryKey;

class OwnerModel extends Model
{
    use BelongsToTenant;
    use HasFactory;
    use HasUuidPrimaryKey;

    protected $table = 'owners';

    protected $fillable = [
        'tenant_id',
        'type',
        'name',
        'document',
        'trade_name',
        'notes',
        'preferred_contact_channel',
        'preferences',
        'responsible_user_id',
        'created_by',
        'last_contacted_at',
    ];

    protected function casts(): array
    {
        return [
            'type' => OwnerType::class,
            'preferred_contact_channel' => OwnerContactChannel::class,
            'preferences' => 'array',
            'last_contacted_at' => 'datetime',
        ];
    }

    protected static function newFactory(): OwnerFactory
    {
        return OwnerFactory::new();
    }

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

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

    public function contacts(): HasMany
    {
        return $this->hasMany(OwnerContactModel::class, 'owner_id');
    }

    public function addresses(): HasMany
    {
        return $this->hasMany(OwnerAddressModel::class, 'owner_id');
    }

    public function documents(): HasMany
    {
        return $this->hasMany(OwnerDocumentModel::class, 'owner_id');
    }

    public function opportunities(): HasMany
    {
        return $this->hasMany(ListingOpportunityModel::class, 'owner_id');
    }

    public function agreements(): HasMany
    {
        return $this->hasMany(ListingAgreementModel::class, 'owner_id');
    }

    public function properties(): BelongsToMany
    {
        return $this->belongsToMany(PropertyModel::class, 'property_owners', 'owner_id', 'property_id')
            ->withPivot(['tenant_id', 'is_primary', 'ownership_share'])
            ->withTimestamps();
    }
}
