<?php

namespace App\Models;

use App\Enums\ReviewStatus;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\Auth;

class Review extends Model
{
    protected $fillable = [
        'ride_id',
        'user_id',
        'rating',
        'title',
        'content',
        'status',
        'moderated_at',
        'moderated_by',
        'helpful_votes_count',
    ];

    protected $casts = [
        'status' => ReviewStatus::class,
        'moderated_at' => 'datetime',
        'rating' => 'integer',
        'helpful_votes_count' => 'integer',
    ];

    // Relationships
    public function ride(): BelongsTo
    {
        return $this->belongsTo(Ride::class);
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

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

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

    // Scopes
    public function scopePending($query)
    {
        return $query->where('status', ReviewStatus::PENDING);
    }

    public function scopeApproved($query)
    {
        return $query->where('status', ReviewStatus::APPROVED);
    }

    public function scopeRejected($query)
    {
        return $query->where('status', ReviewStatus::REJECTED);
    }

    public function scopeByRide($query, $rideId)
    {
        return $query->where('ride_id', $rideId);
    }

    public function scopeByUser($query, $userId)
    {
        return $query->where('user_id', $userId);
    }

    // Methods
    public function approve(): bool
    {
        return $this->moderate(ReviewStatus::APPROVED);
    }

    public function reject(): bool
    {
        return $this->moderate(ReviewStatus::REJECTED);
    }

    public function moderate(ReviewStatus $status, ?int $moderatorId = null): bool
    {
        return $this->update([
            'status' => $status,
            'moderated_at' => now(),
            'moderated_by' => $moderatorId ?? Auth::id(),
        ]);
    }

    public function toggleHelpfulVote(int $userId): bool
    {
        $vote = $this->helpfulVotes()->where('user_id', $userId)->first();

        if ($vote) {
            $vote->delete();
            $this->decrement('helpful_votes_count');
            return false;
        }

        $this->helpfulVotes()->create(['user_id' => $userId]);
        $this->increment('helpful_votes_count');
        return true;
    }
}