<?php

namespace App\Http\Controllers\Api\V1\Product;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\V1\Product\StoreProductRequest;
use App\Http\Requests\Api\V1\Product\UpdateProductRequest;
use App\Http\Requests\Api\V1\Product\BranchProductRequest;
use App\Services\ProductService;
use App\Services\ResponseService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ProductController extends Controller
{
    public function __construct(
        protected ProductService $productService,
        protected ResponseService $responseService
    ) {}

    public function index(): JsonResponse
    {
        $products = $this->productService->getAll();
        return $this->responseService->success($products, 'Products retrieved successfully');
    }

    public function active(): JsonResponse
    {
        $products = $this->productService->getActive();
        return $this->responseService->success($products, 'Active products retrieved successfully');
    }

    public function byCategory(int $categoryId): JsonResponse
    {
        $products = $this->productService->getByCategory($categoryId);
        return $this->responseService->success($products, 'Products by category retrieved successfully');
    }

    public function store(StoreProductRequest $request): JsonResponse
    {
        $product = $this->productService->create($request->validated());
        return $this->responseService->success($product, 'Product created successfully', 201);
    }

    public function show(int $id): JsonResponse
    {
        $product = $this->productService->findWithRelations($id);

        if (!$product) {
            return $this->responseService->error('Product not found', 404);
        }

        return $this->responseService->success($product, 'Product retrieved successfully');
    }

    public function update(UpdateProductRequest $request, int $id): JsonResponse
    {
        $product = $this->productService->find($id);

        if (!$product) {
            return $this->responseService->error('Product not found', 404);
        }

        $product = $this->productService->update($id, $request->validated());
        return $this->responseService->success($product, 'Product updated successfully');
    }

    public function destroy(int $id): JsonResponse
    {
        $product = $this->productService->find($id);

        if (!$product) {
            return $this->responseService->error('Product not found', 404);
        }

        $this->productService->delete($id);
        return $this->responseService->success(null, 'Product deleted successfully');
    }

    public function uploadImage(Request $request, int $id): JsonResponse
    {
        $product = $this->productService->find($id);

        if (!$product) {
            return $this->responseService->error('Product not found', 404);
        }

        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,webp|max:2048',
        ]);

        // Delete old image if exists
        if (!empty($product->image) && Storage::disk('public')->exists($product->image)) {
            Storage::disk('public')->delete($product->image);
        }

        $file = $request->file('image');

        // Generate unique filename
        $filename = uniqid() . '_' . time() . '.' . $file->getClientOriginalExtension();

        // Move file to storage
        $file->move(storage_path('app/public/products'), $filename);

        $path = 'products/' . $filename;

        // Update product with new image path
        $product = $this->productService->update($id, ['image' => $path]);

        return $this->responseService->success($product, 'Product image uploaded successfully');
    }

    public function deleteImage(int $id): JsonResponse
    {
        $product = $this->productService->find($id);

        if (!$product) {
            return $this->responseService->error('Product not found', 404);
        }

        if (!empty($product->image) && Storage::disk('public')->exists($product->image)) {
            Storage::disk('public')->delete($product->image);
        }

        $product = $this->productService->update($id, ['image' => null]);

        return $this->responseService->success($product, 'Product image deleted successfully');
    }

    // Branch Product Management
    public function forBranch(int $branchId): JsonResponse
    {
        $products = $this->productService->getForBranch($branchId);
        return $this->responseService->success($products, 'Branch products retrieved successfully');
    }

    public function assignToBranch(Request $request, int $branchId, int $productId): JsonResponse
    {
        $branchProduct = $this->productService->assignToBranch($branchId, $productId, $request->only(['is_available', 'custom_price']));
        return $this->responseService->success($branchProduct, 'Product assigned to branch successfully', 201);
    }

    public function updateBranchProduct(BranchProductRequest $request, int $branchId, int $productId): JsonResponse
    {
        $branchProduct = $this->productService->updateBranchProduct($branchId, $productId, $request->validated());
        return $this->responseService->success($branchProduct, 'Branch product updated successfully');
    }

    public function bulkAssignToBranch(Request $request, int $branchId): JsonResponse
    {
        $request->validate([
            'product_ids' => 'required|array',
            'product_ids.*' => 'exists:products,id',
        ]);

        $branchProducts = $this->productService->bulkAssignToBranch($branchId, $request->product_ids);
        return $this->responseService->success($branchProducts, 'Products assigned to branch successfully');
    }
}
