<?php

namespace App\Http\Controllers;

use App\Models\Family;
use App\Models\FamilyWallPost;
use App\Models\FamilyWallPostReaction;
use App\Services\ActivityLogger;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class FamilyWallPostReactionController extends Controller
{
    public function __construct(private ActivityLogger $activityLogger)
    {
    }

    public function index(Request $request, Family $family, FamilyWallPost $wallPost)
    {
        $this->authorizeView($request, $family, $wallPost);

        $reactions = $wallPost->reactions()->with('user')->get();

        return response()->json($reactions);
    }

    public function store(Request $request, Family $family, FamilyWallPost $wallPost)
    {
        $this->authorizeReact($request, $family, $wallPost);

        $data = $request->validate([
            'type' => ['required', 'string', Rule::in(['like', 'love', 'celebrate', 'insightful', 'support'])],
            'meta' => ['nullable', 'array'],
        ]);

        $reaction = $wallPost->reactions()->updateOrCreate(
            ['user_id' => $request->user()->id],
            [
                'type' => $data['type'],
                'meta' => $data['meta'] ?? null,
            ]
        );

        $this->activityLogger->log('wall_post.reacted', $reaction, [
            'family_id' => $family->id,
            'wall_post_id' => $wallPost->id,
            'type' => $reaction->type,
        ], $request, $family->id);

        return response()->json($reaction->fresh('user'), 201);
    }

    public function destroy(Request $request, Family $family, FamilyWallPost $wallPost)
    {
        $this->authorizeReact($request, $family, $wallPost);

        $reaction = $wallPost->reactions()->where('user_id', $request->user()->id)->first();

        if (!$reaction) {
            return response()->json(['message' => 'Reaction not found'], 404);
        }

        $reaction->delete();

        $this->activityLogger->log('wall_post.reaction_removed', null, [
            'family_id' => $family->id,
            'wall_post_id' => $wallPost->id,
            'user_id' => $request->user()->id,
        ], $request, $family->id);

        return response()->json(['message' => 'Reaction removed']);
    }

    private function authorizeView(Request $request, Family $family, FamilyWallPost $wallPost): void
    {
        abort_unless($wallPost->family_id === $family->id, 404);

        $user = $request->user();
        $isMember = $family->members()->where('person_id', optional($user->person)->id)->exists();
        abort_unless($user?->can('families.manage') || $isMember, 403);
    }

    private function authorizeReact(Request $request, Family $family, FamilyWallPost $wallPost): void
    {
        $this->authorizeView($request, $family, $wallPost);
    }
}
