<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Concerns\HandlesWidgetCors;
use App\Http\Controllers\Controller;
use App\Models\Contact;
use App\Models\Message;
use App\Models\Organization;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class WidgetMessageCorrectionController extends Controller
{
    use HandlesWidgetCors;

    public function store(Request $request, Message $message): JsonResponse
    {
        $data = $request->validate([
            'widget_key' => ['required', 'string', 'max:80'],
            'visitor_id' => ['required', 'string', 'max:120'],
            'suggested_reply' => ['required', 'string', 'max:1000'],
        ]);

        $organization = Organization::query()
            ->where('widget_public_key', $data['widget_key'])
            ->where('widget_enabled', true)
            ->first();

        if ($organization === null) {
            return $this->jsonWithCors($request, response()->json([
                'message' => 'Widget is not available.',
            ], 404));
        }

        if (! $this->originAllowed($organization, $request->headers->get('origin'))) {
            return $this->jsonWithCors($request, response()->json([
                'message' => 'Origin is not allowed for this widget.',
            ], 403), $organization);
        }

        $contact = Contact::query()
            ->where('organization_id', $organization->id)
            ->where('external_id', $data['visitor_id'])
            ->first();

        if ($contact === null || $message->conversation->contact_id !== $contact->id || $message->conversation->organization_id !== $organization->id) {
            return $this->jsonWithCors($request, response()->json([
                'message' => 'Unauthorized.',
            ], 403), $organization);
        }

        \App\Models\ReportedCorrection::create([
            'organization_id' => $organization->id,
            'conversation_id' => $message->conversation_id,
            'message_id' => $message->id,
            'contact_id' => $contact->id,
            'suggested_reply' => $data['suggested_reply'],
            'status' => 'pending',
        ]);

        return $this->jsonWithCors($request, response()->json(['success' => true]), $organization);
    }
}
