<?php

namespace App\Services;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\ProductReview;
use App\Models\ProductVariant;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class ReviewService {

    public function getProductReviewItem($orderId)
    {
        $products = OrderItem::select([
            'uuid',
            'product_variant_id',
            'product_image_url_snapshot',
            'product_name_snapshot',
            'product_variant_name_snapshot',

        ])
        ->where('order_id', $orderId)
        ->get();

        return $products;
    }

    public function reviewProduct($data, $orderId)
    {
        $tenantId = config('app.current_tenant_id');
        DB::transaction(function () use ($data, $orderId, $tenantId) {
            foreach ($data as $item) {
                ProductReview::create([
                    'uuid' => (string) Str::uuid7(),
                    'tenant_id' => $tenantId,
                    'customer_id' => $item['customer_id'],
                    'product_variant_id' => $item['product_variant_id'],
                    'rating' => $item['rating'],
                    'comment' => $item['comment']
                ]);

                $productVariant = ProductVariant::lockForUpdate()
                    ->where('uuid', $item['product_variant_id'])
                    ->first();

                if ($productVariant) {
                    $newTotalRatingCount = $productVariant->total_rating + 1;
                    
                    $sumRating = ProductReview::where('product_variant_id', $item['product_variant_id'])
                    ->sum('rating');
                    
                    $newAverage = $sumRating / $newTotalRatingCount;

                    $productVariant->update([
                        'total_rating' => $newTotalRatingCount,
                        'average_rating' => $newAverage
                    ]);
                }
            }

            Order::where('uuid', $orderId)->update([
                'has_been_assessed' => true
            ]);
        });
    }
}