<?php

namespace App\Http\Controllers\api\v1\Admin;

use App\Http\Controllers\Controller;
use App\Models\Vendor;
use App\Service\Admin\VendorService;
use App\Traits\JsonResponseTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class VendorController extends Controller
{
    use JsonResponseTrait;

    protected $vendorService;

    public function __construct(VendorService $vendorService)
    {
        $this->vendorService = $vendorService;
    }



    /**
     * Show a specific vendor .
     */
    public function getVendor($track_id = null)
    {
        if ($track_id) {
            $vendor = Vendor::where('track_id', $track_id)->first();
            if (!$vendor) {
                return $this->errorResponse(403, 'Vendor  not found');
            }
            return response()->json($vendor);
        }

        // No track_id provided – return all
        $allvendors = Vendor::all();
        return response()->json($allvendors);
    }


    /**
     * Update an existing vendor .
     */
    public function updateVendor(Request $request)
    {
        // Validate that track_id is present in the request
        $request->validate([
            'track_id' => 'required|string|exists:vendors,track_id',
        ]);

        // Get the  using track_id from the request body
        $vendor = Vendor::where('track_id', $request->track_id)->first();

        if (!$vendor) {
            return $this->errorResponse(404, 'Vendor  not found');
        }

        // Perform the update
        $updated = $this->vendorService->updateVendor($vendor, $request->all());

        return response()->json([
            'status' => true,
            'message' => 'Vendor updated successfully',
            'data' => $updated,
        ]);
    }



    /**
     * Delete a vendor .
     */
    public function deleteVendor(Request $request)
    {
        // Validate input
        $request->validate([
            'track_id' => 'required|string|exists:vendor_categories,track_id',
        ]);

        $deleted = $this->vendorService->deleteVendor($request->track_id);

        if (!$deleted) {
            return $this->errorResponse(404, 'Vendor  not found or already deleted');
        }

        return $this->successDataResponse(200, message: 'Vendor  deleted successfully');

    }
}
