<?php

namespace App\Http\Controllers\App;

use App\Http\Controllers\Controller;
use App\Http\Requests\ProposalUpdateRequest;
use App\Models\Opportunity;
use App\Models\ProposalDocument;
use App\Services\Ai\AiGenerationService;
use App\Support\ActivityLogger;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;
use Illuminate\View\View;

class ProposalController extends Controller
{
    public function draft(Request $request, Opportunity $opportunity, AiGenerationService $aiGenerationService): RedirectResponse
    {
        if (! $request->user()->isExecutive()) {
            abort_unless(
                $opportunity->owner_user_id === $request->user()->id || $opportunity->affiliate_user_id === $request->user()->id,
                403
            );
        }

        $version = $aiGenerationService->draftProposal($opportunity);

        ActivityLogger::log('proposal.drafted', $request->user(), $version, [], $version->toArray(), $request);

        return redirect()->route('app.proposals.show', $version->proposal_document_id)->with('success', 'Draft proposal created.');
    }

    public function show(ProposalDocument $proposalDocument): View
    {
        Gate::authorize('manage-proposal', $proposalDocument);

        return view('app.proposals.show', [
            'proposalDocument' => $proposalDocument->load(['opportunity', 'clientContact', 'versions']),
            'latestVersion' => $proposalDocument->latestVersion()->first(),
        ]);
    }

    public function update(ProposalUpdateRequest $request, ProposalDocument $proposalDocument): RedirectResponse
    {
        Gate::authorize('manage-proposal', $proposalDocument);

        $latestVersion = $proposalDocument->latestVersion()->first();
        $mergedContent = array_merge($latestVersion?->content ?? [], $request->input('content', []));
        $status = $request->input('status', $proposalDocument->status);

        $version = $proposalDocument->versions()->create([
            'created_by_user_id' => $request->user()->id,
            'version_number' => (($proposalDocument->versions()->max('version_number')) ?? 0) + 1,
            'status' => $status,
            'content' => $mergedContent,
            'change_summary' => $request->input('change_summary'),
        ]);

        $proposalDocument->update([
            'status' => $status,
            'controlled_terms_status' => ! empty($mergedContent['controlled_terms']) ? 'pending_review' : 'approved',
        ]);

        ActivityLogger::log('proposal.edited', $request->user(), $version, [], $version->toArray(), $request);

        return back()->with('success', 'Proposal draft saved as a new version.');
    }

    public function share(Request $request, ProposalDocument $proposalDocument): RedirectResponse
    {
        Gate::authorize('manage-proposal', $proposalDocument);

        if (! $proposalDocument->share_token) {
            $proposalDocument->share_token = Str::uuid()->toString();
        }

        $proposalDocument->status = 'shared_with_client';
        $proposalDocument->shared_at = now();
        $proposalDocument->save();

        $link = URL::temporarySignedRoute(
            'client.proposals.show',
            now()->addDays(14),
            ['proposalDocument' => $proposalDocument->share_token]
        );

        ActivityLogger::log('proposal.shared', $request->user(), $proposalDocument, [], ['share_link' => $link], $request);

        return back()->with('success', 'Signed client link generated.')->with('share_link', $link);
    }
}
