<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Batch;
use App\Models\EconomicScenario;
use App\Support\BatchKpiSnapshotService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class RasEconomicController extends Controller
{
    public function snapshots(): JsonResponse
    {
        $userId = (int) auth('api')->id();
        BatchKpiSnapshotService::ensureHistoricalCoverageForUser($userId);
        $items = BatchKpiSnapshotService::latestSnapshotsForUser($userId);

        if ($items->isEmpty()) {
            $batches = Batch::query()
                ->with('tank')
                ->where('user_id', $userId)
                ->whereIn('status', ['active', 'closing', 'closed'])
                ->orderBy('id')
                ->get();
            BatchKpiSnapshotService::syncMany($batches);
            $items = BatchKpiSnapshotService::latestSnapshotsForUser($userId);
        }

        return $this->success($items->values(), 'Economic snapshots');
    }

    public function growthTrends(): JsonResponse
    {
        $userId = (int) auth('api')->id();
        BatchKpiSnapshotService::ensureHistoricalCoverageForUser($userId);
        $items = BatchKpiSnapshotService::growthTrendsForUser($userId);

        if ($items->isEmpty()) {
            $batches = Batch::query()
                ->with('tank')
                ->where('user_id', $userId)
                ->whereIn('status', ['active', 'closing', 'closed'])
                ->orderBy('id')
                ->get();
            BatchKpiSnapshotService::syncMany($batches);
            $items = BatchKpiSnapshotService::growthTrendsForUser($userId);
        }

        return $this->success($items->values(), 'Economic growth trends');
    }

    public function scenarios(): JsonResponse
    {
        $userId = (int) auth('api')->id();

        $items = EconomicScenario::query()
            ->where('user_id', $userId)
            ->orderBy('name')
            ->get()
            ->map(fn (EconomicScenario $scenario) => $this->mapScenario($scenario))
            ->values();

        if ($items->isEmpty()) {
            $items = collect([[
                'id' => 'sc_base',
                'name' => 'Base',
                'sale_price_crc_per_kg' => 3500,
                'expected_mortality_pct' => 2,
                'feed_cost_variation_pct' => 0,
                'energy_cost_variation_pct' => 0,
                'growth_variation_pct' => 0,
                'result' => [
                    'projected_margin_crc' => 0,
                    'projected_cost_per_kg_crc' => 0,
                    'break_even_reached' => false,
                ],
            ]]);
        }

        return $this->success($items->values(), 'Economic scenarios');
    }

    public function upsertScenario(Request $request): JsonResponse
    {
        $userId = (int) auth('api')->id();
        $data = $request->validate([
            'id' => ['nullable', 'string', 'max:60'],
            'name' => ['required', 'string', 'max:120'],
            'sale_price_crc_per_kg' => ['required', 'numeric', 'min:0'],
            'expected_mortality_pct' => ['required', 'numeric', 'min:0', 'max:100'],
            'feed_cost_variation_pct' => ['required', 'numeric', 'min:-100', 'max:999'],
            'energy_cost_variation_pct' => ['required', 'numeric', 'min:-100', 'max:999'],
            'growth_variation_pct' => ['required', 'numeric', 'min:-100', 'max:999'],
            'result' => ['nullable', 'array'],
            'result.projected_margin_crc' => ['nullable', 'numeric'],
            'result.projected_cost_per_kg_crc' => ['nullable', 'numeric'],
            'result.break_even_reached' => ['nullable', 'boolean'],
        ]);

        $id = $this->numericIdFromClient((string) ($data['id'] ?? ''));

        $scenario = null;
        if ($id > 0) {
            $scenario = EconomicScenario::query()->where('user_id', $userId)->find($id);
        }

        if (! $scenario) {
            $scenario = new EconomicScenario();
            $scenario->user_id = $userId;
        }

        $scenario->name = (string) $data['name'];
        $scenario->sale_price_crc_per_kg = (float) $data['sale_price_crc_per_kg'];
        $scenario->expected_mortality_pct = (float) $data['expected_mortality_pct'];
        $scenario->feed_cost_variation_pct = (float) $data['feed_cost_variation_pct'];
        $scenario->energy_cost_variation_pct = (float) $data['energy_cost_variation_pct'];
        $scenario->growth_variation_pct = (float) $data['growth_variation_pct'];
        $scenario->result = $data['result'] ?? [
            'projected_margin_crc' => 0,
            'projected_cost_per_kg_crc' => 0,
            'break_even_reached' => false,
        ];
        $scenario->save();

        return $this->success($this->mapScenario($scenario), 'Scenario saved');
    }

    public function deleteScenario(string $id): JsonResponse
    {
        $userId = (int) auth('api')->id();
        $numericId = $this->numericIdFromClient($id);
        if ($numericId <= 0) {
            return $this->error('Invalid scenario id', null, 422);
        }

        $scenario = EconomicScenario::query()->where('user_id', $userId)->find($numericId);
        if (! $scenario) {
            return $this->error('Scenario not found', null, 404);
        }

        $scenario->delete();

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

    private function numericIdFromClient(string $id): int
    {
        if (preg_match('/(\d+)$/', $id, $m)) {
            return (int) $m[1];
        }

        return 0;
    }

    private function mapScenario(EconomicScenario $scenario): array
    {
        $result = is_array($scenario->result) ? $scenario->result : [];

        return [
            'id' => 'sc_' . (int) $scenario->id,
            'name' => (string) $scenario->name,
            'sale_price_crc_per_kg' => (float) $scenario->sale_price_crc_per_kg,
            'expected_mortality_pct' => (float) $scenario->expected_mortality_pct,
            'feed_cost_variation_pct' => (float) $scenario->feed_cost_variation_pct,
            'energy_cost_variation_pct' => (float) $scenario->energy_cost_variation_pct,
            'growth_variation_pct' => (float) $scenario->growth_variation_pct,
            'result' => [
                'projected_margin_crc' => (float) ($result['projected_margin_crc'] ?? 0),
                'projected_cost_per_kg_crc' => (float) ($result['projected_cost_per_kg_crc'] ?? 0),
                'break_even_reached' => (bool) ($result['break_even_reached'] ?? false),
            ],
        ];
    }
}
