<?php

namespace App\Http\Controllers\Care;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Services\Identity\IdentityTeamClient;
use App\Support\StaffUx;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class IssueReportController extends Controller
{
    use ScopesToAccount;

    public function create(Request $request): View
    {
        abort_unless(! StaffUx::showBilling($request->user()), 403);

        return view('care.issues.create');
    }

    public function store(Request $request, IdentityTeamClient $identity): RedirectResponse
    {
        abort_unless(! StaffUx::showBilling($request->user()), 403);

        $validated = $request->validate([
            'subject' => ['required', 'string', 'max:255'],
            'message' => ['required', 'string', 'max:5000'],
            'priority' => ['required', 'in:low,normal,high'],
        ]);

        $user = $request->user();
        $organization = $this->organization($request);
        $member = $this->member($request);

        $context = trim(implode("\n", array_filter([
            'App: Ladill Care',
            'Organization: '.($organization->name ?? '—'),
            'Role: '.($member?->role ?? '—'),
            'Reporter: '.($user->email ?? $user->ownerRef()),
            '',
            $validated['message'],
        ])));

        try {
            $ticket = $identity->createSupportTicket($user->ownerRef(), [
                'subject' => $validated['subject'],
                'message' => $context,
                'priority' => $validated['priority'],
                'tags' => ['staff_issue', 'app:care'],
            ], 'care');
        } catch (\Throwable $e) {
            report($e);

            return back()
                ->withInput()
                ->with('error', 'Could not send your report right now. Please try again in a moment.');
        }

        $ref = (string) ($ticket['ticket_ref'] ?? '');

        return redirect()
            ->route('care.dashboard')
            ->with('success', $ref !== ''
                ? "Issue reported to Ladill support ({$ref}). Our team will follow up."
                : 'Issue reported to Ladill support. Our team will follow up.');
    }
}
