<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Support\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class TwoFactorSecurityController extends Controller
{
    public function show(Request $request)
    {
        $user = $request->user();

        return ApiResponse::success([
            'channel' => $user->two_factor_channel,
            'enabled_for_login' => (bool) $user->two_factor_enabled_for_login,
            'enabled_for_withdrawal' => (bool) $user->two_factor_enabled_for_withdrawal,
            'enabled_for_project_activation' => (bool) $user->two_factor_enabled_for_project_activation,
        ]);
    }

    public function update(Request $request)
    {
        $data = $request->validate([
            'channel' => ['nullable', 'string', Rule::in(['sms', 'email'])],
            'enabled_for_login' => ['sometimes', 'boolean'],
            'enabled_for_withdrawal' => ['sometimes', 'boolean'],
            'enabled_for_project_activation' => ['sometimes', 'boolean'],
        ]);

        $user = $request->user();
        $user->fill([
            'two_factor_channel' => $data['channel'] ?? $user->two_factor_channel,
            'two_factor_enabled_for_login' => $data['enabled_for_login'] ?? $user->two_factor_enabled_for_login,
            'two_factor_enabled_for_withdrawal' => $data['enabled_for_withdrawal'] ?? $user->two_factor_enabled_for_withdrawal,
            'two_factor_enabled_for_project_activation' => $data['enabled_for_project_activation'] ?? $user->two_factor_enabled_for_project_activation,
        ])->save();

        return ApiResponse::success([
            'channel' => $user->two_factor_channel,
            'enabled_for_login' => (bool) $user->two_factor_enabled_for_login,
            'enabled_for_withdrawal' => (bool) $user->two_factor_enabled_for_withdrawal,
            'enabled_for_project_activation' => (bool) $user->two_factor_enabled_for_project_activation,
        ], 'تنظیمات احراز هویت دو مرحله‌ای ذخیره شد.');
    }
}
