<?php

namespace App\Http\Controllers\Api\V1;

use App\Domain\Financial\Models\InvoiceItem;
use App\Domain\Inventory\Models\Product;
use App\Domain\Participant\Models\Participant;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ShopController extends Controller
{
    public function products(Request $request): JsonResponse
    {
        $user = $request->user();

        $products = Product::where('is_active', true)
            ->where('is_essential', true)
            ->orderBy('name_ar')
            ->with('installmentPlans')
            ->get();

        $participantUuid = $request->query('participant_uuid');
        $participant = null;

        if ($participantUuid) {
            $participant = Participant::where('uuid', $participantUuid)->first();
        }

        $productType = 'App\\Domain\\Inventory\\Models\\Product';
        $yearStart = now()->startOfYear();

        return response()->json([
            'data' => $products->map(function ($product) use ($participant, $productType, $yearStart) {
                $alreadyPurchasedAt = null;

                if ($participant) {
                    $previousPurchase = InvoiceItem::where('itemable_type', $productType)
                        ->where('itemable_id', $product->id)
                        ->where('created_at', '>=', $yearStart)
                        ->whereHas('invoice', fn ($q) => $q
                            ->where('billable_type', 'App\\Domain\\Participant\\Models\\Participant')
                            ->where('billable_id', $participant->id)
                            ->whereNotIn('status', ['cancelled', 'draft'])
                        )
                        ->orderByDesc('created_at')
                        ->first();

                    $alreadyPurchasedAt = $previousPurchase?->created_at?->format('Y-m-d');
                }

                return [
                    'id' => $product->id,
                    'name_ar' => $product->name_ar,
                    'name' => $product->name,
                    'sku' => $product->sku,
                    'selling_price' => $product->selling_price,
                    'photo_url' => $product->photo_path ? asset('storage/' . $product->photo_path) : null,
                    'already_purchased_at' => $alreadyPurchasedAt,
                    'installment_plans' => $product->installmentPlans->map(fn ($plan) => [
                        'id' => $plan->id,
                        'name_ar' => $plan->name_ar ?? $plan->name,
                        'installments_count' => $plan->installments_count,
                        'down_payment' => $plan->down_payment,
                    ]),
                ];
            }),
        ]);
    }
}
