<?php

namespace App\Controllers\Api\V1;

use App\Controllers\BaseController;
use App\Services\Messaging\MessagingService;

class MessagingController extends BaseController
{
    private MessagingService $messaging;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->messaging = new MessagingService();
    }

    public function index()
    {
        $user = $this->currentUser();
        return $this->jsonSuccess(['conversations' => $this->messaging->conversationsFor($user->id)]);
    }

    public function start()
    {
        $user = $this->currentUser();
        $input = $this->request->getJSON(true);

        if (empty($input['recipient_user_id'])) {
            return $this->jsonValidationError(['recipient_user_id' => 'recipient_user_id is required.']);
        }

        $initiatorAgencyId = $user->isCandidate() ? null : $user->agency_id;

        try {
            $conversation = $this->messaging->startConversation(
                $user->id,
                (int) $input['recipient_user_id'],
                $input['job_application_id'] ?? null,
                $initiatorAgencyId
            );
        } catch (\App\Exceptions\InsufficientCreditsException $e) {
            return $this->jsonError([['code' => 'INSUFFICIENT_CREDITS', 'message' => $e->getMessage()]], 402);
        }

        return $this->jsonSuccess(['conversation' => $conversation], [], 201);
    }

    public function messages(int $conversationId)
    {
        $user = $this->currentUser();
        $page = (int) ($this->request->getGet('page') ?? 1);

        try {
            $messages = $this->messaging->messagesFor($conversationId, $user->id, $page);
        } catch (\App\Exceptions\ForbiddenException $e) {
            return $this->jsonError([['code' => 'FORBIDDEN', 'message' => $e->getMessage()]], 403);
        }

        return $this->jsonSuccess(['messages' => $messages]);
    }

    public function send(int $conversationId)
    {
        $user = $this->currentUser();
        $input = $this->request->getJSON(true);

        if (empty($input['body'])) {
            return $this->jsonValidationError(['body' => 'Message body is required.']);
        }

        try {
            $message = $this->messaging->sendMessage($conversationId, $user->id, $input['body']);
        } catch (\App\Exceptions\ForbiddenException $e) {
            return $this->jsonError([['code' => 'FORBIDDEN', 'message' => $e->getMessage()]], 403);
        }

        return $this->jsonSuccess(['message' => $message], [], 201);
    }

    public function markRead(int $conversationId)
    {
        $user = $this->currentUser();
        $this->messaging->markRead($conversationId, $user->id);
        return $this->jsonSuccess(['message' => 'Marked as read.']);
    }
}
