<?php

namespace App\Http\Controllers\Api\Email;

use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\Email\EmailExtractorCompareRequest;
use App\Http\Resources\Email\EmailExtractorCompareResource;
use App\Http\Resources\Email\EmailExtractorEmailsResource;
use App\Services\Email\EmailExtractorService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class EmailExtractorController extends BaseApiController
{
    public function __construct(private EmailExtractorService $service)
    {
        parent::__construct();
    }

    public function emails(): JsonResponse
    {
        $emails = $this->service->listEmails();

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

    public function compare(EmailExtractorCompareRequest $request): JsonResponse
    {
        $csvEmails = [];

        $file = $request->file('file');
        if ($file && $file->isValid()) {
            $contents = file_get_contents($file->getRealPath() ?: $file->getPathname());
            $csvEmails = $this->service->extractEmailsFromText($contents);
        }

        if (empty($csvEmails)) {
            $csvEmails = $request->input('csv_emails', []);
        }

        if (empty($csvEmails)) {
            return response()->json([
                'ok' => false,
                'message' => 'Provide a CSV file or csv_emails array.',
            ], 422);
        }

        $result = $this->service->compare($csvEmails);

        return response()->json([
            'ok' => true,
            'comparison' => new EmailExtractorCompareResource($result),
        ]);
    }
}
