<?php

namespace App\Http\Controllers\API\v1\Election;

use App\Election;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Util;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class RegisterNextSessionController extends Controller
{
    public function __invoke(Request $request)
    {
        $this->validateRequest($request);

        if (Util::getElectionStatus() !== 3) {
            return response()->json([
                'status' => 'failed',
                'message' => 'Daftar sesi baharu hanya tersedia selepas undian telah tamat.',
            ], 422);
        }

        Util::ensureDraftElectionAfterCompletedCycle();

        $election = Election::find(Util::getCurrentElection());
        if ($request->filled('name')) {
            $election->update(['name' => $request->name]);
        }

        $user = $request->user();
        activity()
            ->withProperties([
                'election_id' => (int) $election->id,
                'election_name' => (string) $request->input('name', ''),
                'registered_by_admin_id' => $user ? (int) $user->id : null,
                'registered_by_admin_email' => $user ? $user->email : null,
                'ip' => $request->ip(),
                'user_agent' => $request->userAgent(),
            ])
            ->log('election register next session');

        return response()->json([
            'status' => 'success',
            'message' => 'Sesi mengundi baharu didaftarkan. Sila lengkapkan maklumat calon sebelum memulakan undian.',
            'election' => $election->fresh(),
        ]);
    }

    private function validateRequest($request)
    {
        $id = Auth::id();
        $this->validate($request, [
            'password' => 'required|password:users,password,' . $id,
            'name' => 'nullable|string|max:60',
        ]);
    }
}
