<?php

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

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\V1\Production\StoreProductionBatchRequest;
use App\Http\Requests\Api\V1\Production\UpdateProductionBatchRequest;
use App\Http\Requests\Api\V1\Production\StoreBatchSizeConfigRequest;
use App\Http\Requests\Api\V1\Production\UpdateBatchSizeConfigRequest;
use App\Http\Requests\Api\V1\Production\RecordBatchWasteRequest;
use App\Services\ProductionBatchService;
use App\Services\ResponseService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ProductionBatchController extends Controller
{
    public function __construct(
        protected ProductionBatchService $batchService,
        protected ResponseService $responseService
    ) {}

    // =============================================
    // BATCH SIZE CONFIGURATIONS
    // =============================================

    public function batchSizeConfigs(): JsonResponse
    {
        $configs = $this->batchService->getBatchSizeConfigs();
        return $this->responseService->success($configs, 'Batch size configurations retrieved successfully');
    }

    public function storeBatchSizeConfig(StoreBatchSizeConfigRequest $request): JsonResponse
    {
        $config = $this->batchService->createBatchSizeConfig($request->validated());
        return $this->responseService->success($config, 'Batch size configuration created successfully', 201);
    }

    public function updateBatchSizeConfig(UpdateBatchSizeConfigRequest $request, int $id): JsonResponse
    {
        try {
            $config = $this->batchService->updateBatchSizeConfig($id, $request->validated());
            return $this->responseService->success($config, 'Batch size configuration updated successfully');
        } catch (\InvalidArgumentException $e) {
            return $this->responseService->error($e->getMessage(), 404);
        }
    }

    public function destroyBatchSizeConfig(int $id): JsonResponse
    {
        try {
            $this->batchService->deleteBatchSizeConfig($id);
            return $this->responseService->success(null, 'Batch size configuration deleted successfully');
        } catch (\InvalidArgumentException $e) {
            return $this->responseService->error($e->getMessage(), 404);
        }
    }

    // =============================================
    // PRODUCTION BATCHES
    // =============================================

    public function index(Request $request): JsonResponse
    {
        $filters = $request->only(['branch_id', 'product_id', 'status', 'date', 'start_date', 'end_date']);
        $batches = $this->batchService->getAllBatches($filters);
        return $this->responseService->success($batches, 'Production batches retrieved successfully');
    }

    public function active(Request $request): JsonResponse
    {
        $branchId = $request->input('branch_id');
        $productId = $request->input('product_id');

        if (!$branchId) {
            return $this->responseService->error('branch_id is required', 422);
        }

        $batches = $this->batchService->getActiveBatches($branchId, $productId);
        return $this->responseService->success($batches, 'Active batches retrieved successfully');
    }

    public function store(StoreProductionBatchRequest $request): JsonResponse
    {
        try {
            $data = $request->validated();
            $data['produced_by'] = auth()->id();

            $batch = $this->batchService->createBatch($data);
            return $this->responseService->success($batch, 'Production batch created successfully. Ingredients have been deducted from inventory.', 201);
        } catch (\InvalidArgumentException $e) {
            return $this->responseService->error($e->getMessage(), 422);
        } catch (\Exception $e) {
            return $this->responseService->error('Failed to create batch: ' . $e->getMessage(), 500);
        }
    }

    public function show(int $id): JsonResponse
    {
        $batch = $this->batchService->getBatchDetails($id);

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

        return $this->responseService->success($batch, 'Production batch retrieved successfully');
    }

    public function update(UpdateProductionBatchRequest $request, int $id): JsonResponse
    {
        try {
            $batch = $this->batchService->updateBatch($id, $request->validated());
            return $this->responseService->success($batch, 'Production batch updated successfully');
        } catch (\InvalidArgumentException $e) {
            return $this->responseService->error($e->getMessage(), 404);
        }
    }

    public function cancel(Request $request, int $id): JsonResponse
    {
        try {
            $reason = $request->input('reason');
            $batch = $this->batchService->cancelBatch($id, $reason);
            return $this->responseService->success($batch, 'Production batch cancelled successfully');
        } catch (\InvalidArgumentException $e) {
            return $this->responseService->error($e->getMessage(), 422);
        }
    }

    public function recordWaste(RecordBatchWasteRequest $request, int $id): JsonResponse
    {
        try {
            $batch = $this->batchService->recordBatchWaste(
                $id,
                $request->scoop_count,
                $request->reason
            );
            return $this->responseService->success($batch, 'Batch waste recorded successfully');
        } catch (\InvalidArgumentException $e) {
            return $this->responseService->error($e->getMessage(), 422);
        }
    }

    public function markExpired(): JsonResponse
    {
        $count = $this->batchService->markExpiredBatches();
        return $this->responseService->success(
            ['expired_count' => $count],
            "{$count} batch(es) marked as expired"
        );
    }

    // =============================================
    // SCOOP SALES REPORTS
    // =============================================

    public function dailySummary(Request $request): JsonResponse
    {
        $branchId = $request->input('branch_id');
        $date = $request->input('date', now()->toDateString());

        if (!$branchId) {
            return $this->responseService->error('branch_id is required', 422);
        }

        $summary = $this->batchService->getDailyScoopSummary($branchId, $date);
        return $this->responseService->success($summary, 'Daily scoop summary retrieved successfully');
    }

    public function dailySales(Request $request): JsonResponse
    {
        $branchId = $request->input('branch_id');
        $date = $request->input('date', now()->toDateString());

        if (!$branchId) {
            return $this->responseService->error('branch_id is required', 422);
        }

        $sales = $this->batchService->getDailySalesByProduct($branchId, $date);
        $totalScoops = $this->batchService->getTotalScoopsSold($branchId, $date);

        return $this->responseService->success([
            'date' => $date,
            'total_scoops_sold' => $totalScoops,
            'sales_by_product' => $sales,
        ], 'Daily sales report retrieved successfully');
    }

    public function salesReport(Request $request): JsonResponse
    {
        $request->validate([
            'branch_id' => 'required|integer|exists:branches,id',
            'start_date' => 'required|date',
            'end_date' => 'required|date|after_or_equal:start_date',
        ]);

        $sales = $this->batchService->getSalesReport(
            $request->branch_id,
            $request->start_date,
            $request->end_date
        );

        return $this->responseService->success($sales, 'Sales report retrieved successfully');
    }
}
