<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Mail\SupportRequestMail;
use App\Models\SupportRequest;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

/**
 * G7-A: приём клиентских заявок в техподдержку. Запись в БД — основной канал;
 * письмо в поддержку — best-effort (сбой SMTP не валит запрос, паттерн G1 sendCode).
 */
class SupportRequestController extends Controller
{
    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'contact' => 'required|string|max:255',
            'message' => 'required|string|max:5000',
        ]);

        /** @var User $user */
        $user = $request->user();

        $supportRequest = DB::transaction(function () use ($user, $validated): SupportRequest {
            DB::statement('SET LOCAL app.current_tenant_id = '.(int) $user->tenant_id);

            return SupportRequest::create([
                'tenant_id' => $user->tenant_id,
                'user_id' => $user->id,
                'name' => $validated['name'],
                'contact' => $validated['contact'],
                'message' => $validated['message'],
            ]);
        });

        // Письмо — best-effort: заявка уже в БД, сбой почты не теряет её и не валит запрос.
        try {
            Mail::to(config('services.support.email'))->queue(new SupportRequestMail($supportRequest));
        } catch (\Throwable $e) {
            Log::warning('SupportRequestMail queue failed', ['id' => $supportRequest->id, 'error' => $e->getMessage()]);
        }

        return response()->json(['ok' => true], 201);
    }
}
