<?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;
use Illuminate\Support\Facades\Auth;

/**
 * @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 $gateway_customer_id
 * @property string|null $gateway_customer_code
 * @property int|null $profile_media_id
 * @property bool $selfie_verified
 * @property string|null $idempotency_key
 * @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 whereGatewayCustomerCode($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Client whereGatewayCustomerId($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Client whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Client whereIdempotencyKey($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|Client whereProfileMediaId($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',
        'gateway_customer_id',
        'gateway_customer_code',
        'idempotency_key',
        'user_id',
        'profile_media_id',
        'selfie_verified',
    ];

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

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

    //

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

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

    public function profileMedia(): BelongsTo
    {
        $authenticatedUser = Auth::user();

        $relation = $this->belongsTo(Media::class, 'profile_media_id')
            ->join('clients as profile_media_clients', function ($join) {
                $join->on('profile_media_clients.id', '=', 'media.source_id')
                    ->on('profile_media_clients.profile_media_id', '=', 'media.id');
            })
            ->where('media.source', 'client')
            ->select('media.*');

        if ($authenticatedUser?->canModerateClients()) {
            return $relation;
        }

        return $relation->where(function ($query) use ($authenticatedUser) {
            $query->where('profile_media_clients.selfie_verified', true);

            if ($authenticatedUser !== null) {
                $query->orWhere('profile_media_clients.user_id', $authenticatedUser->id);
            }
        });
    }

    public function schedules()
    {
        return $this->hasMany(Schedule::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 ensureGatewayCode(): string
    {
        if (! empty($this->gateway_customer_code)) {
            return $this->gateway_customer_code;
        }

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

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

        return $code;
    }
}
