<?php

namespace App\Http\Controllers\Ranch;

use App\Http\Controllers\Controller;
use App\Models\Cattle;
use App\Models\CattleCalvingEvent;
use App\Models\CattleSaleIncome;
use App\Models\FatteningLot;
use App\Models\MaterialExpense;
use App\Models\MaterialType;
use App\Services\FatteningLotAnalyticsService;
use App\Services\FeedStockService;
use App\Services\PastureService;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class MobileBootstrapController extends Controller
{
    public function __construct(
        private readonly PastureService $pastureService,
        private readonly FeedStockService $feedStockService,
        private readonly FatteningLotAnalyticsService $analyticsService,
    ) {}

    /**
     * Catálogos + permisos + resumen para la app móvil (menos round-trips en campo).
     */
    public function __invoke(Request $request): JsonResponse
    {
        $user = $request->user();
        $monthStart = Carbon::now()->startOfMonth();
        $monthEnd = Carbon::now()->endOfMonth();

        $openLots = FatteningLot::query()
            ->open()
            ->withCount(['activeAnimals as animals_count'])
            ->orderByDesc('entry_date')
            ->get(['id', 'name', 'status', 'entry_date'])
            ->map(function (FatteningLot $lot) {
                $analytics = $this->analyticsService->forLot($lot);
                $breakdown = $analytics['investment_breakdown'] ?? [];
                $projection = $analytics['projection'] ?? [];

                return [
                    'id' => $lot->id,
                    'name' => $lot->name,
                    'status' => $lot->status,
                    'entry_date' => $lot->entry_date?->toDateString(),
                    'animals_count' => $lot->animals_count,
                    'summary' => [
                        'total_investment' => $breakdown['total'] ?? null,
                        'feed_cost' => $breakdown['feed_cost'] ?? null,
                        'health_cost' => $breakdown['health_cost'] ?? null,
                        'estimated_sale_total' => $projection['projected_income'] ?? null,
                        'estimated_net_profit' => $projection['projected_net_profit'] ?? null,
                    ],
                ];
            })
            ->values();

        $feedMaterials = MaterialType::query()
            ->active()
            ->where('category', 'feed_supplements')
            ->orderBy('name')
            ->get(['id', 'name', 'unit', 'category', 'default_unit_price', 'stock_quantity']);

        $healthMaterials = MaterialType::query()
            ->active()
            ->where('category', config('ranch.health.material_category', 'animal_health'))
            ->orderBy('name')
            ->get(['id', 'name', 'unit', 'category', 'default_unit_price', 'stock_quantity']);

        return response()->json([
            'data' => [
                'user' => [
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                ],
                'permissions' => $user->getAllPermissions()->pluck('name')->values(),
                'catalog' => [
                    'statuses' => config('ranch.cattle_statuses'),
                    'genders' => config('ranch.genders'),
                    'ear_tag_types' => config('ranch.ear_tag_types'),
                    'material_categories' => config('ranch.material_categories'),
                    'health_event_types' => config('ranch.health_event_types'),
                    'health_outcomes' => config('ranch.health_outcomes'),
                    'pastures' => $this->pastureService->listForCatalog(),
                    'feed_materials' => $feedMaterials,
                    'feed_inventory' => $this->feedStockService->feedInventory(),
                    'health_materials' => $healthMaterials,
                ],
                'open_fattening_lots' => $openLots,
                'media_base_url' => rtrim((string) config('app.url'), '/'),
                'dashboard' => [
                    'active_cattle' => Cattle::active()->count(),
                    'sold_this_month' => Cattle::where('status', Cattle::STATUS_SOLD)
                        ->whereBetween('deactivated_at', [$monthStart, $monthEnd])->count(),
                    'deaths_this_month' => Cattle::where('status', Cattle::STATUS_DEAD)
                        ->whereBetween('deactivated_at', [$monthStart, $monthEnd])->count(),
                    'open_fattening_lots' => $openLots->count(),
                    'expenses_this_month' => (float) MaterialExpense::whereBetween('expense_date', [$monthStart, $monthEnd])->sum('total_cost'),
                    'income_this_month' => (float) CattleSaleIncome::whereBetween('sale_date', [$monthStart, $monthEnd])->sum('total_price'),
                    'calvings_this_month' => CattleCalvingEvent::whereBetween('calving_date', [$monthStart, $monthEnd])->count(),
                ],
            ],
        ]);
    }
}
