<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class ModeratorController extends Controller
{
    /** GET /api/admin/moderators */
    public function index(Request $request): JsonResponse
    {
        $tenant = app('tenant');

        $moderators = DB::table('moderators')
            ->where('tenant_id', $tenant->id)
            ->orderByDesc('created_at')
            ->get()
            ->map(function ($mod) {
                $mod->permissions = $mod->permissions ? json_decode($mod->permissions, true) : [];
                unset($mod->password); // never expose password hash
                return $mod;
            });

        return response()->json(['success' => true, 'data' => $moderators]);
    }

    /** POST /api/admin/moderators */
    public function store(Request $request): JsonResponse
    {
        $tenant = app('tenant');

        $email    = trim($request->input('email', ''));
        $name     = trim($request->input('name', ''));
        $password = $request->input('password', '');
        $permissions = $request->input('permissions', []);

        if (!$email || !$name || !$password) {
            return response()->json(['success' => false, 'error' => 'Name, email and password are required'], 422);
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return response()->json(['success' => false, 'error' => 'Invalid email format'], 422);
        }

        if (strlen($password) < 6) {
            return response()->json(['success' => false, 'error' => 'Password must be at least 6 characters'], 422);
        }

        // Check for duplicate email within this tenant
        $exists = DB::table('moderators')
            ->where('tenant_id', $tenant->id)
            ->where('email', $email)
            ->exists();

        if ($exists) {
            return response()->json(['success' => false, 'error' => 'A moderator with this email already exists'], 409);
        }

        $id = DB::table('moderators')->insertGetId([
            'tenant_id'   => $tenant->id,
            'name'        => $name,
            'email'       => $email,
            'password'    => Hash::make($password),
            'role'        => 'moderator',
            'permissions' => json_encode($permissions),
            'created_at'  => now(),
            'updated_at'  => now(),
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Moderator created successfully',
            'data'    => ['id' => $id],
        ], 201);
    }

    /** PUT /api/admin/moderators/{id} */
    public function update(Request $request, int $id): JsonResponse
    {
        $tenant = app('tenant');

        $moderator = DB::table('moderators')
            ->where('id', $id)
            ->where('tenant_id', $tenant->id)
            ->first();

        if (!$moderator) {
            return response()->json(['success' => false, 'error' => 'Moderator not found'], 404);
        }

        $update = [
            'name'        => trim($request->input('name', $moderator->name)),
            'permissions' => json_encode($request->input('permissions', [])),
            'updated_at'  => now(),
        ];

        if ($request->filled('password')) {
            if (strlen($request->input('password')) < 6) {
                return response()->json(['success' => false, 'error' => 'Password must be at least 6 characters'], 422);
            }
            $update['password'] = Hash::make($request->input('password'));
        }

        DB::table('moderators')->where('id', $id)->update($update);

        return response()->json(['success' => true, 'message' => 'Moderator updated successfully']);
    }

    /** DELETE /api/admin/moderators/{id} */
    public function destroy(int $id): JsonResponse
    {
        $tenant = app('tenant');

        $deleted = DB::table('moderators')
            ->where('id', $id)
            ->where('tenant_id', $tenant->id)
            ->delete();

        if (!$deleted) {
            return response()->json(['success' => false, 'error' => 'Moderator not found'], 404);
        }

        return response()->json(['success' => true, 'message' => 'Moderator deleted successfully']);
    }
}
