<?php

namespace App\Http\Controllers\AiPortal;

use App\Models\AiAutomationSettings;
use App\Services\AuditLogger;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

/**
 * Read + update the AI automation singleton (auto-draft toggle, auto-reply
 * toggle, office-hours schedule, live-execution toggle, min-confidence).
 */
class AiAutomationSettingsController extends Controller
{
    public function show(Request $request)
    {
        abort_unless($request->user()->isAdminOrAbove(), 403);
        $row = AiAutomationSettings::current();
        return response()->json([
            'settings'    => $row,
            'staff_online' => $row->staffOnline(),
            'should_auto_reply_now' => $row->shouldAutoReplyNow(),
            'all_days' => AiAutomationSettings::ALL_DAYS,
        ]);
    }

    public function update(Request $request)
    {
        abort_unless($request->user()->isAdminOrAbove(), 403);

        $data = $request->validate([
            'auto_draft_enabled'             => ['nullable', 'boolean'],
            'auto_reply_enabled'             => ['nullable', 'boolean'],
            'auto_reply_only_when_offline'   => ['nullable', 'boolean'],
            'auto_reply_mode'                => ['nullable', 'in:always,outside_office_hours,custom_window'],
            'auto_reply_delay_minutes'       => ['nullable', 'integer', 'between:0,1440'],
            // HH:MM or HH:MM:SS — coerced to seconds before save.
            'office_hours_start'             => ['nullable', 'string', 'regex:/^\d{2}:\d{2}(:\d{2})?$/'],
            'office_hours_end'               => ['nullable', 'string', 'regex:/^\d{2}:\d{2}(:\d{2})?$/'],
            'office_days'                    => ['nullable', 'array'],
            'office_days.*'                  => ['string', 'in:mon,tue,wed,thu,fri,sat,sun'],
            'custom_window_start'            => ['nullable', 'string', 'regex:/^\d{2}:\d{2}(:\d{2})?$/'],
            'custom_window_end'              => ['nullable', 'string', 'regex:/^\d{2}:\d{2}(:\d{2})?$/'],
            // Customer-nudge controls (status = Answered, waiting on customer).
            'nudge_waiting_customer_enabled' => ['nullable', 'boolean'],
            'nudge_interval_hours'           => ['nullable', 'integer', 'between:1,720'],
            'nudge_max_count'                => ['nullable', 'integer', 'between:1,10'],
            // Internal admin-note assistance per department.
            'admin_note_assist_enabled'      => ['nullable', 'boolean'],
            'ns_diagnostic_enabled'          => ['nullable', 'boolean'],
            'email_diagnostic_enabled'       => ['nullable', 'boolean'],
            'admin_note_assist_departments'  => ['nullable', 'array'],
            'admin_note_assist_departments.*'=> ['string', 'max:64'],
            'admin_note_assist_interval_hours' => ['nullable', 'integer', 'between:1,168'],
            'admin_note_assist_use_schedule' => ['nullable', 'boolean'],
            'admin_note_window_start'        => ['nullable', 'string', 'regex:/^\d{2}:\d{2}(:\d{2})?$/'],
            'admin_note_window_end'          => ['nullable', 'string', 'regex:/^\d{2}:\d{2}(:\d{2})?$/'],
            'admin_note_window_days'         => ['nullable', 'array'],
            'admin_note_window_days.*'       => ['string', 'in:mon,tue,wed,thu,fri,sat,sun'],
            'min_confidence'                 => ['nullable', 'numeric', 'between:0,1'],
            'live_execution'                 => ['nullable', 'boolean'],
            // Server-action policy — see AiAutomationSettings::POLICY_*
            'ai_server_action_policy'        => ['nullable', 'in:block,propose_only,auto_low_risk_ok'],
        ]);

        foreach (['office_hours_start', 'office_hours_end',
                  'custom_window_start', 'custom_window_end',
                  'admin_note_window_start', 'admin_note_window_end'] as $f) {
            if (isset($data[$f]) && strlen($data[$f]) === 5) {
                $data[$f] .= ':00';
            }
        }

        $row = AiAutomationSettings::current();
        $row->fill([...$data, 'updated_by' => $request->user()->id])->save();

        AuditLogger::log('user', (string) $request->user()->id, $request->user()->email,
            'ai_automation.updated', 'ai_automation_settings', (string) $row->id,
            ['changed' => array_keys($data)], $request);

        // Bust the per-request cache so the next call to current() reflects.
        return response()->json([
            'settings'    => $row->fresh(),
            'staff_online' => $row->fresh()->staffOnline(),
            'should_auto_reply_now' => $row->fresh()->shouldAutoReplyNow(),
        ]);
    }

    /**
     * Trigger an immediate one-shot pass of the auto-reply pipeline. Same
     * logic the scheduler runs every 5 min, but operators can hit this
     * button to verify the pipeline works without waiting (and without
     * needing `php artisan schedule:run` cron set up).
     */
    public function runAutoReplyNow(Request $request)
    {
        abort_unless($request->user()->isAdminOrAbove(), 403);

        // Long timeout because each dispatched job runs synchronously
        // (drafter + WHMCS POST per ticket can take 10–20 s each).
        @set_time_limit(600);
        ini_set('max_execution_time', '600');

        \Illuminate\Support\Facades\Artisan::call('ai:auto-reply-once');
        $output = \Illuminate\Support\Facades\Artisan::output();

        AuditLogger::log('user', (string) $request->user()->id, $request->user()->email,
            'ai_automation.run_auto_reply_now', 'ai_automation_settings', null,
            ['output_excerpt' => mb_substr($output, 0, 500, 'UTF-8')], $request);

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