<?php
namespace App\Services;
use App\Models\{Project,Review,PointEntry,PointRule,User};
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class Reviews {
 public function invite(Project $p,?\App\Models\ServicePeriod $servicePeriod=null):void {
  $period=$servicePeriod??$p->currentPeriod()??$p->periods()->orderByDesc('starts_at')->first();if(!$period)return;
  if(Review::where('service_period_id',$period->id)->where('user_id',$p->customer_id)->exists())return;
  $token=Str::random(64);$review=Review::firstOrCreate(['service_period_id'=>$period->id,'user_id'=>$p->customer_id],['project_id'=>$p->id,'token_hash'=>hash('sha256',$token),'token_expires_at'=>now()->addDays(30)]);
  if($review->wasRecentlyCreated)app(Notify::class)->event('review_invite',$p,['review_url'=>url('/review-link/'.$token),'notification_url'=>url('/reviews/'.$review->id)],"review:$review->id",$p->customer);
 }
 public function moderate(User $actor,Review $review,string $status,string $reason):void {
  abort_unless($actor->canAdmin('reviews')&&$actor->id!==$review->project->mentor_id,403);
  DB::transaction(function()use($actor,$review,$status,$reason){$r=Review::lockForUpdate()->findOrFail($review->id);Access::project($actor,$r->project);$oldStatus=$r->status;$r->update(['status'=>$status,'moderation_reason'=>$reason]);
   $rule=PointRule::where('code','review_'.$r->kind)->where('active',true)->first();$target=$status==='accepted'?($rule?->points??0):0;$reference='review:'.$r->id;$earned=(int)PointEntry::where('reference',$reference)->where('user_id',$r->user_id)->sum('points');
   if($target!==$earned)PointEntry::create(['event_key'=>Str::uuid(),'user_id'=>$r->user_id,'actor_id'=>$actor->id,'reference'=>$reference,'points'=>$target-$earned,'title'=>'امتیاز تجربه منتورینگ','rule_version'=>$rule?->version??1]);if($target>$earned)app(Notify::class)->event('points',$r->project,['points'=>$target-$earned,'action_title'=>'ثبت تجربه','notification_url'=>url('/club')],"review-points:$r->id:$target",$r->user);Access::audit('review_moderated',$r->id,['status'=>$status,'reason'=>$reason]);
  });
 }
}
