<?php

namespace App\Http\Controllers\Api\Frontend;

use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\Frontend\ContactSubmitRequest;
use App\Http\Resources\Frontend\ContactSubmissionResource;
use App\Http\Resources\Frontend\PageContentResource;
use App\Services\Frontend\ContactSubmissionService;
use App\Services\Frontend\StaticPageService;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

class PageController extends BaseApiController
{
    public function __construct(
        private StaticPageService $pageService,
        private ContactSubmissionService $contactService
    ) {
        parent::__construct();
    }

    public function privacyPolicy(): JsonResponse
    {
        return $this->renderStatic('privacy_policy.html', 'privacy_policy');
    }

    public function termsOfService(): JsonResponse
    {
        return $this->renderStatic('terms_of_service.html', 'terms_of_service');
    }

    public function helpCenter(): JsonResponse
    {
        return $this->renderStatic('help_center.html', 'help_center');
    }

    public function submitContact(ContactSubmitRequest $request): JsonResponse
    {
        $result = $this->contactService->submit($request->validated());

        return $this->success([
            'submission' => new ContactSubmissionResource([
                'email' => $request->validated('email'),
                'email_sent' => $result['email_sent'],
                'contact_id' => $result['record']?->id,
            ]),
        ], 'Message received.', Response::HTTP_CREATED);
    }

    private function renderStatic(string $filename, string $type): JsonResponse
    {
        $result = $this->pageService->load($filename, $type);
        if (!$result['ok']) {
            return $this->error($result['error'], Response::HTTP_NOT_FOUND);
        }

        return $this->success([
            'page' => new PageContentResource($result),
        ]);
    }
}
