<?php

namespace App\Http\Controllers\App;

use App\Http\Controllers\Controller;
use App\Http\Requests\MeetingStoreRequest;
use App\Models\Meeting;
use App\Models\Opportunity;
use App\Services\Ai\AiGenerationService;
use App\Support\ActivityLogger;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\View\View;

class MeetingController extends Controller
{
    public function store(MeetingStoreRequest $request): RedirectResponse
    {
        $opportunity = Opportunity::findOrFail($request->integer('opportunity_id'));
        $this->authorizeOpportunityAccess($request, $opportunity);
        $lead = $opportunity->lead;

        $meeting = Meeting::create([
            'account_id' => $opportunity->account_id,
            'contact_id' => $opportunity->primary_contact_id,
            'opportunity_id' => $opportunity->id,
            'owner_user_id' => $request->user()->id,
            'title' => $request->title,
            'scheduled_at' => $request->scheduled_at,
            'meeting_type' => $request->input('meeting_type', 'discovery'),
            'meeting_source' => $request->input('meeting_source', 'manual'),
            'status' => 'scheduled',
            'attendees' => [$lead?->name, $request->user()->name],
            'summary_status' => 'not_started',
        ]);

        if ($request->filled('raw_notes')) {
            $meeting->notes()->create([
                'created_by_user_id' => $request->user()->id,
                'raw_notes' => $request->raw_notes,
                'visibility_level' => 'internal',
            ]);
        }

        ActivityLogger::log('meeting.created', $request->user(), $meeting, [], $meeting->toArray(), $request);

        return redirect()->route('app.meetings.show', $meeting)->with('success', 'Meeting created.');
    }

    public function show(Request $request, Meeting $meeting): View
    {
        $this->authorizeMeetingAccess($request, $meeting);

        return view('app.meetings.show', [
            'meeting' => $meeting->load(['notes.author', 'opportunity', 'contact', 'account']),
        ]);
    }

    public function addNote(Request $request, Meeting $meeting): RedirectResponse
    {
        $this->authorizeMeetingAccess($request, $meeting);

        $validated = $request->validate([
            'raw_notes' => ['required', 'string'],
            'internal_notes' => ['nullable', 'string'],
            'client_facing_notes' => ['nullable', 'string'],
        ]);

        $note = $meeting->notes()->create([
            'created_by_user_id' => $request->user()->id,
            'raw_notes' => $validated['raw_notes'],
            'internal_notes' => $validated['internal_notes'] ?? null,
            'client_facing_notes' => $validated['client_facing_notes'] ?? null,
            'visibility_level' => 'internal',
        ]);

        ActivityLogger::log('meeting.notes_added', $request->user(), $note, [], $note->toArray(), $request);

        return back()->with('success', 'Meeting note saved.');
    }

    public function summarize(Request $request, Meeting $meeting, AiGenerationService $aiGenerationService): RedirectResponse
    {
        $this->authorizeMeetingAccess($request, $meeting);

        $run = $aiGenerationService->summarizeMeeting($meeting);

        $meeting->update(['summary_status' => 'draft_ready']);

        ActivityLogger::log('ai.summary_generated', $request->user(), $run, [], $run->toArray(), $request);

        return back()->with('success', 'AI summary drafted and stored for review.');
    }

    private function authorizeOpportunityAccess(Request $request, Opportunity $opportunity): void
    {
        if ($request->user()->isExecutive()) {
            return;
        }

        abort_unless(
            $opportunity->owner_user_id === $request->user()->id || $opportunity->affiliate_user_id === $request->user()->id,
            403
        );
    }

    private function authorizeMeetingAccess(Request $request, Meeting $meeting): void
    {
        if ($request->user()->isExecutive()) {
            return;
        }

        abort_unless(
            $meeting->owner_user_id === $request->user()->id || $meeting->opportunity?->affiliate_user_id === $request->user()->id,
            403
        );
    }
}
