<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Return\StoreReturnRequest;
use App\Http\Resources\ReturnResource;
use App\Models\Order;
use App\Models\SaleReturn;
use App\Services\ReturnService;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

class ReturnController extends ApiController
{
    public function __construct(private readonly ReturnService $returnService)
    {
    }

    public function index(Request $request): AnonymousResourceCollection
    {
        $returns = SaleReturn::query()
            ->with(['originalOrder', 'customer'])
            ->where('company_id', $this->currentCompanyId($request))
            ->where('branch_id', $this->currentBranchId($request))
            ->latest('id')
            ->paginate((int) $request->integer('per_page', 15));

        return ReturnResource::collection($returns);
    }

    public function store(StoreReturnRequest $request): ReturnResource
    {
        $order = Order::query()
            ->with('items')
            ->findOrFail($request->integer('original_order_id'));

        $this->ensureCompanyScoped($order, $this->currentCompanyId($request));
        $this->ensureBranchScoped($order, $this->currentBranchId($request));

        $saleReturn = $this->returnService->create(
            $this->currentUser($request),
            $order,
            $request->validated(),
        );

        return new ReturnResource($saleReturn);
    }
}
