<?php

namespace App\Models;

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;

/**
 * @property int $id
 * @property string|null $document
 * @property int $user_id
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @property \Illuminate\Support\Carbon|null $deleted_at
 * @property string|null $average_rating
 * @property int $total_services
 * @property string|null $external_customer_id
 * @property string|null $external_customer_code
 * @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\ProviderClientBlock> $blockedByProviders
 * @property-read int|null $blocked_by_providers_count
 * @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\ClientProviderBlock> $blockedProviders
 * @property-read int|null $blocked_providers_count
 * @property-read \App\Models\Media|null $profileMedia
 * @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\Schedule> $schedules
 * @property-read int|null $schedules_count
 * @property-read \App\Models\User $user
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Client newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Client newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Client onlyTrashed()
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Client query()
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Client whereAverageRating($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Client whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Client whereDeletedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Client whereDocument($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Client whereExternalCustomerCode($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Client whereExternalCustomerId($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Client whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Client whereTotalServices($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Client whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Client whereUserId($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Client withTrashed(bool $withTrashed = true)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Client withoutTrashed()
 * @mixin \Eloquent
 */
class Client extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'document',
        'external_customer_id',
        'external_customer_code',
        'user_id',
        'profile_media_id',
    ];

    protected $casts = [
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime',
    ];

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class)->select('id', 'name', 'email', 'phone');
    }

    public function profileMedia(): BelongsTo
    {
        return $this->belongsTo(Media::class, 'profile_media_id');
    }

    public function blockedByProviders(): HasMany
    {
        return $this->hasMany(ProviderClientBlock::class);
    }

    public function blockedProviders(): HasMany
    {
        return $this->hasMany(ClientProviderBlock::class);
    }

    public function updateAverageRating(float $newRating): void
    {
        $totalReviews = Review::where('reviews.origin', 'provider')
            ->leftJoin('schedules', 'schedules.id', '=', 'reviews.schedule_id')
            ->where('schedules.client_id', $this->id)
            ->count();

        if ($totalReviews === 0) {
            $this->average_rating = $newRating;
        } else {
            $currentTotalRating   = $this->average_rating * ($totalReviews - 1);
            $newAverage           = ($currentTotalRating + $newRating) / $totalReviews;
            $this->average_rating = round($newAverage, 2);
        }

        $this->save();
    }

    public function schedules()
    {
        return $this->hasMany(Schedule::class);
    }

    //

    public function ensureGatewayCode(): string
    {
        if (! empty($this->external_customer_code)) {
            return $this->external_customer_code;
        }

        $code = 'client-'.(string) \Illuminate\Support\Str::uuid();

        $this->forceFill(['external_customer_code' => $code])->save();

        return $code;
    }
}
