<?php

namespace App\Http\Controllers\Api\V1\Admin;

use App\Http\Controllers\Controller;
use App\Models\ChatGroup;
use App\Models\ChatGroupMember;
use App\Models\User;
use Illuminate\Http\Request;

class ChatGroupController extends Controller
{
    public function index(Request $request)
    {
        $groups = ChatGroup::with('event:id,name')
            ->withCount('members')
            ->latest()
            ->paginate(20);

        return $this->paginated($groups);
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'event_id' => ['required', 'integer', 'exists:events,id'],
            'name'     => ['required', 'string', 'max:255'],
        ]);

        $group = ChatGroup::create([
            ...$data,
            'created_by_admin_id' => $request->user()->id,
            'status'              => 'active',
        ]);

        return $this->created($group->load('event:id,name'), 'Chat group created.');
    }

    public function update(Request $request, ChatGroup $group)
    {
        $data = $request->validate([
            'name'   => ['sometimes', 'string', 'max:255'],
            'status' => ['sometimes', 'in:active,archived'],
        ]);

        $group->update($data);

        return $this->success($group->fresh()->load('event:id,name'), 'Chat group updated.');
    }

    public function destroy(Request $request, ChatGroup $group)
    {
        $group->delete();

        return $this->noContent('Chat group deleted.');
    }

    public function addMember(Request $request, ChatGroup $group)
    {
        $data = $request->validate([
            'user_id' => ['required', 'integer', 'exists:users,id'],
            'role'    => ['sometimes', 'in:member,group_admin,agency_admin'],
        ]);

        $member = ChatGroupMember::firstOrCreate(
            ['chat_group_id' => $group->id, 'user_id' => $data['user_id']],
            ['role' => $data['role'] ?? 'member', 'joined_at' => now()]
        );

        return $this->created(
            $member->load('user:id,name,its_number'),
            'Member added to group.'
        );
    }

    public function removeMember(Request $request, ChatGroup $group, User $user)
    {
        ChatGroupMember::where('chat_group_id', $group->id)
            ->where('user_id', $user->id)
            ->delete();

        return $this->noContent('Member removed.');
    }

    public function assignAdmin(Request $request, ChatGroup $group, User $user)
    {
        $data = $request->validate([
            'role' => ['required', 'in:member,group_admin,agency_admin'],
        ]);

        $updated = ChatGroupMember::where('chat_group_id', $group->id)
            ->where('user_id', $user->id)
            ->update(['role' => $data['role']]);

        if (! $updated) {
            return $this->notFound('User is not a member of this group.');
        }

        return $this->success(null, 'Role updated.');
    }
}
