<?php

namespace App\Http\Controllers\API\V1;

use App\Http\Controllers\Controller;
use App\Http\Requests\HistoryRequest;
use App\Http\Resources\HistoryResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class HistoryController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $perPage = $request->query('per_page', 15);

        $histories = $request->user()
            ->histories()
            ->with('product.category')
            ->latest()
            ->paginate($perPage);

        return response()->json([
            'data' => HistoryResource::collection(
                $histories->load('product.category')
            ),
            'meta' => [
                'current_page' => $histories->currentPage(),
                'per_page' => $histories->perPage(),
                'total' => $histories->total(),
                'last_page' => $histories->lastPage(),
                'from' => $histories->firstItem(),
                'to' => $histories->lastItem(),
            ],
        ]);
    }

    public function store(HistoryRequest $request): JsonResponse
    {
        $history = $request->user()->histories()->firstOrCreate([
            'product_id' => $request->validated('product_id'),
            'action' => $request->validated('action', 'view'),
        ]);

        $history->load('product.category');

        return response()->json([
            'data' => HistoryResource::make($history),
        ]);
    }
}
