<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Concerns\ResolvesCurrentOrganization;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class AiModelConfigController extends Controller
{
    use ResolvesCurrentOrganization;

    public function edit(Request $request): View
    {
        $organization = $this->currentOrganization($request);
        abort_if($organization === null, 404);
        abort_unless($this->currentUserCan($request, 'manage_settings'), 403);

        return view('settings.ai-model', compact('organization'));
    }

    public function update(Request $request): RedirectResponse
    {
        $organization = $this->currentOrganization($request);
        abort_if($organization === null, 404);
        abort_unless($this->currentUserCan($request, 'manage_settings'), 403);

        $data = $request->validate([
            'ai_provider' => ['required', 'string', 'in:none,ollama,openai,gemini,anthropic'],
            'ai_model' => ['required', 'string', 'max:255'],
            'ai_api_key' => ['nullable', 'string', 'max:1000'],
            'ai_api_url' => ['nullable', 'url', 'max:1000'],
        ]);

        $organization->update([
            'ai_provider' => $data['ai_provider'],
            'ai_model' => $data['ai_model'],
            'ai_api_key' => $data['ai_api_key'],
            'ai_api_url' => $data['ai_api_url'],
        ]);

        return redirect()->route('settings.ai-model.edit')->with('status', 'AI Model configuration updated successfully.');
    }
}
