<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Concerns\ResolvesCurrentOrganization;
use App\Models\UnknownQuestion;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class UnknownQuestionResolutionController extends Controller
{
    use ResolvesCurrentOrganization;

    public function store(Request $request, UnknownQuestion $unknownQuestion): RedirectResponse
    {
        $organization = $this->currentOrganization($request);

        abort_unless($organization !== null && $unknownQuestion->organization_id === $organization->id, 404);
        abort_unless($this->currentUserCan($request, 'train_ai'), 403);

        $action = $request->input('resolution_action', 'resolve');

        if ($action === 'assign_intent') {
            $data = $request->validate([
                'intent_id' => ['required', 'exists:intents,id'],
            ]);

            $intent = $organization->intents()->find($data['intent_id']);
            if ($intent) {
                $intent->intentPhrases()->create([
                    'organization_id' => $organization->id,
                    'locale' => $unknownQuestion->locale,
                    'phrase' => $unknownQuestion->body,
                    'status' => 'approved',
                ]);
            }
        } elseif ($action === 'create_intent') {
            $data = $request->validate([
                'new_intent_name' => ['required', 'string', 'max:255'],
                'new_response_body' => ['required', 'string', 'max:5000'],
            ]);

            $intent = $organization->intents()->create([
                'name' => $data['new_intent_name'],
                'slug' => Str::slug($data['new_intent_name']).'-'.uniqid(),
                'status' => 'active',
                'confidence_threshold' => 0.7500,
            ]);

            $intent->intentPhrases()->create([
                'organization_id' => $organization->id,
                'locale' => $unknownQuestion->locale,
                'phrase' => $unknownQuestion->body,
                'status' => 'approved',
            ]);

            $intent->responseTemplates()->create([
                'organization_id' => $organization->id,
                'locale' => $unknownQuestion->locale,
                'status' => 'approved',
                'body' => $data['new_response_body'],
                'priority' => 100,
            ]);
        }

        $unknownQuestion->forceFill([
            'status' => 'resolved',
            'resolved_by_user_id' => $request->user()->id,
            'resolved_at' => now(),
        ])->save();

        return back()->with('status', 'Unknown question resolved successfully.');
    }
}
