<?php

namespace App\Http\Controllers;

use App\Models\Caso;
use App\Models\ChatMessage;
use App\Models\User;
use App\Services\NotificationService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ChatController extends Controller
{
    public function __construct()
    {
        Carbon::setLocale('es');
    }

    public function index(Caso $caso)
    {
        $messages = ChatMessage::where('caso_id', $caso->id)
            ->with('user', 'ajustador')
            ->orderBy('created_at')
            ->get()
            ->map(function ($msg) {
                return [
                    'id' => $msg->id,
                    'message' => $msg->message,
                    'sender_id' => $msg->user_id ?? $msg->ajustador_id,
                    'sender_name' => $msg->senderName(),
                    'sender_type' => $msg->senderIsAdmin() ? 'admin' : 'ajustador',
                    'created_at' => $msg->created_at->toDateTimeString(),
                    'created_at_diff' => $msg->created_at->diffForHumans(),
                ];
            });

        return response()->json(['messages' => $messages]);
    }

    public function store(Request $request, Caso $caso)
    {
        $request->validate([
            'message' => 'required|string|max:2000',
        ]);

        $data = ['caso_id' => $caso->id, 'message' => $request->message];
        $isAdjuster = $request->is('ajustador/*');

        if ($isAdjuster) {
            $ajustador = Auth::guard('ajustador')->user();
            if (! $ajustador) {
                return response()->json(['error' => 'No autorizado'], 401);
            }
            $data['ajustador_id'] = $ajustador->id;

            $message = ChatMessage::create($data);
            $message->load('user', 'ajustador');

            $admin = User::where('rol', 'admin')->first();
            if ($admin) {
                NotificationService::notify(
                    $caso,
                    'nuevo_mensaje',
                    "Ajustador {$ajustador->nombre} envió un mensaje en el caso {$caso->numero_reclamo}: \"{$request->message}\"",
                    ['ajustador_id' => $ajustador->id, 'chat_message_id' => $message->id]
                );
            }
        } else {
            $user = Auth::guard('web')->user();
            if (! $user) {
                return response()->json(['error' => 'No autorizado'], 401);
            }
            $data['user_id'] = $user->id;

            $message = ChatMessage::create($data);
            $message->load('user', 'ajustador');

            $ajustador = $caso->ajustador;
            if ($ajustador) {
                NotificationService::notify(
                    $caso,
                    'nuevo_mensaje',
                    "Admin envió un mensaje en el caso {$caso->numero_reclamo}: \"{$request->message}\"",
                    ['ajustador_id' => $ajustador->id, 'chat_message_id' => $message->id]
                );
            }
        }

        return response()->json([
            'message' => [
                'id' => $message->id,
                'message' => $message->message,
                'sender_id' => $message->user_id ?? $message->ajustador_id,
                'sender_name' => $message->senderName(),
                'sender_type' => $message->senderIsAdmin() ? 'admin' : 'ajustador',
                'created_at' => $message->created_at->toDateTimeString(),
                'created_at_diff' => $message->created_at->diffForHumans(),
            ],
        ]);
    }
}
