<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Client extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'document',
        'user_id',
    ];

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

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

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

    /**
     * @return HasMany
     */
    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);
    }
}
