<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Batches\StoreBatchRequest;
use App\Http\Requests\Batches\UpdateBatchRequest;
use App\Models\Batch;
use App\Models\Tank;
use Illuminate\Http\JsonResponse;

class BatchController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(): JsonResponse
    {
        $userId = (int) auth('api')->id();
        $batches = Batch::query()->with('tank')->where('user_id', $userId)->latest()->get();

        return $this->success($batches, 'Batches list');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreBatchRequest $request): JsonResponse
    {
        $userId = (int) auth('api')->id();
        $payload = $request->validated();

        $tankId = (int) ($payload['tank_id'] ?? 0);
        $tank = Tank::query()->where('user_id', $userId)->find($tankId);
        if (! $tank) {
            return $this->error('Tank not found', null, 404);
        }

        if (($payload['status'] ?? 'active') === 'active') {
            $hasActive = Batch::query()
                ->where('user_id', $userId)
                ->where('tank_id', $tankId)
                ->where('status', 'active')
                ->exists();

            if ($hasActive) {
                return $this->error('There is already an active batch for this tank', null, 422);
            }
        }

        $batch = Batch::create(array_merge($payload, ['user_id' => $userId]));

        return $this->success($batch->load('tank'), 'Batch created', 201);
    }

    /**
     * Display the specified resource.
     */
    public function show(int $id): JsonResponse
    {
        $userId = (int) auth('api')->id();
        $batch = Batch::query()->with('tank')->where('user_id', $userId)->find($id);

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

        return $this->success($batch, 'Batch details');
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateBatchRequest $request, int $id): JsonResponse
    {
        $userId = (int) auth('api')->id();
        $batch = Batch::query()->where('user_id', $userId)->find($id);

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

        $payload = $request->validated();
        if (array_key_exists('tank_id', $payload)) {
            $tankId = (int) ($payload['tank_id'] ?? 0);
            $tank = Tank::query()->where('user_id', $userId)->find($tankId);
            if (! $tank) {
                return $this->error('Tank not found', null, 404);
            }
        }

        $targetTankId = (int) ($payload['tank_id'] ?? $batch->tank_id);
        $targetStatus = (string) ($payload['status'] ?? $batch->status);
        if ($targetStatus === 'active') {
            $hasActive = Batch::query()
                ->where('user_id', $userId)
                ->where('tank_id', $targetTankId)
                ->where('status', 'active')
                ->where('id', '!=', $batch->id)
                ->exists();

            if ($hasActive) {
                return $this->error('There is already an active batch for this tank', null, 422);
            }
        }

        $batch->update($payload);

        return $this->success($batch->load('tank'), 'Batch updated');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(int $id): JsonResponse
    {
        $userId = (int) auth('api')->id();
        $batch = Batch::query()->where('user_id', $userId)->find($id);

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

        $batch->delete();

        return $this->success(null, 'Batch deleted');
    }
}
