<?php

namespace App\Http\Controllers\Api\Administrator;

use App\Http\Controllers\Controller;
use App\Services\Administrator\AdministratorTeacherSubmissionService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class AdministratorTeacherSubmissionController extends Controller
{
    public function __construct(
        protected AdministratorTeacherSubmissionService $service
    ) {
    }

    public function index(): JsonResponse
    {
        return response()->json($this->service->report());
    }

    public function notify(Request $request): JsonResponse
    {
        $adminId = (int) Auth::id();
        if ($adminId <= 0) {
            return response()->json(['message' => 'Please log in first.'], 401);
        }

        $validator = Validator::make($request->all(), [
            'notify' => ['required', 'array', 'min:1'],
            'missing_items' => ['nullable', 'array'],
        ], [
            'notify.required' => 'Select at least one teacher to notify.',
            'notify.array' => 'Notify payload must be an array.',
            'notify.min' => 'Select at least one teacher to notify.',
            'missing_items.array' => 'Missing items payload must be an array.',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'message' => 'Validation failed.',
                'errors' => $validator->errors(),
            ], 422);
        }

        $result = $this->service->sendNotifications($request, $adminId);

        return response()->json([
            'message' => $result['message'],
            'sent' => $result['sent'] ?? 0,
            'failed' => $result['failed'] ?? 0,
        ], $result['status']);
    }
}
