<?php

namespace App\Http\Controllers\Courier;

use App\Http\Controllers\Controller;
use App\Models\Delivery;
use App\Models\DeliveryRejection;
use Illuminate\Http\Request;
use App\Services\DeliveryAssigner;
use Illuminate\Support\Str;

class ProfileController extends Controller
{
    public function edit(Request $request)
    {
        $user = $request->user();

        // Ensure a connect token exists for Telegram linking.
        if ($user && !$user->telegram_connect_token) {
            $user->forceFill([
                'telegram_connect_token' => Str::random(64),
            ])->save();
        }

        return view('courier.profile', [
            'user' => $user,
        ]);
    }

    public function update(Request $request)
    {
        $data = $request->validate([
            'nav_app' => 'required|in:maps,waze',
            'max_active_orders' => 'required|integer|min:1|max:10',
        ]);

        $request->user()->update($data);

        return redirect()
            ->route('courier.profile.edit')
            ->with('success', 'Preferencia actualizada.');
    }

    public function updateStatus(Request $request)
    {
        $courier = $request->user()->courier;

        if (!$courier) {
            abort(403);
        }

        $data = $request->validate([
            'is_online' => 'required|boolean',
        ]);

        if (!$courier->is_active && $data['is_online']) {
            return redirect()
                ->back()
                ->withErrors(['status' => 'El repartidor está desactivado por el administrador.']);
        }

        $goingOffline = $courier->is_online && !$data['is_online'];
        $courier->update([
            'is_online' => $data['is_online'],
        ]);

        if ($goingOffline) {
            $pendingDeliveries = Delivery::query()
                ->where('courier_id', $courier->id)
                ->where('status', Delivery::STATUS_PENDING)
                ->get();

            $assigner = app(DeliveryAssigner::class);
            foreach ($pendingDeliveries as $delivery) {
                DeliveryRejection::create([
                    'delivery_id' => $delivery->id,
                    'courier_id' => $courier->id,
                    'reason' => 'offline',
                ]);

                $delivery->update([
                    'courier_id' => null,
                    'status' => Delivery::STATUS_PENDING,
                ]);

                $assigner->assignNext($delivery);
            }
        }

        return redirect()
            ->back()
            ->with('success', $data['is_online'] ? 'Estado en línea activado.' : 'Estado en línea desactivado.');
    }

    public function disconnectTelegram(Request $request)
    {
        $user = $request->user();
        $user->forceFill([
            'telegram_chat_id' => null,
            'telegram_connected_at' => null,
            'telegram_connect_token' => Str::random(64),
        ])->save();

        return redirect()
            ->back()
            ->with('success', 'Telegram desconectado.');
    }
}
