<?php

declare(strict_types=1);

// SPDX-FileCopyrightText: Chen Asraf <contact@casraf.dev>
// SPDX-License-Identifier: AGPL-3.0-or-later

namespace OCA\Forum\Controller;

use OCA\Forum\Db\ReadMarkerMapper;
use OCA\Forum\Service\NotificationService;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Attribute\ApiRoute;
use OCP\AppFramework\Http\Attribute\NoAdminRequired;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\OCSController;
use OCP\IRequest;
use OCP\IUserSession;
use Psr\Log\LoggerInterface;

class ReadMarkerController extends OCSController {
	public function __construct(
		string $appName,
		IRequest $request,
		private ReadMarkerMapper $readMarkerMapper,
		private NotificationService $notificationService,
		private IUserSession $userSession,
		private LoggerInterface $logger,
	) {
		parent::__construct($appName, $request);
	}

	/**
	 * Get read markers for multiple threads
	 *
	 * @param string $threadIds Array of thread IDs (comma-separated in query string)
	 * @param string $markerType Marker type ('thread' or 'category')
	 * @return DataResponse<Http::STATUS_OK, array<string, array{entityId: int, lastReadPostId: int|null, readAt: int}>, array{}>
	 *
	 * 200: Read markers returned (keyed by entity ID)
	 */
	#[NoAdminRequired]
	#[ApiRoute(verb: 'GET', url: '/api/read-markers')]
	public function index(string $threadIds = '', string $markerType = 'thread'): DataResponse {
		try {
			$user = $this->userSession->getUser();
			if (!$user) {
				return new DataResponse(['error' => 'User not authenticated'], Http::STATUS_UNAUTHORIZED);
			}

			// Category markers
			if ($markerType === 'category') {
				$markers = $this->readMarkerMapper->findCategoryMarkersByUserId($user->getUID());
				$result = [];
				foreach ($markers as $marker) {
					$result[$marker->getEntityId()] = [
						'entityId' => $marker->getEntityId(),
						'readAt' => $marker->getReadAt(),
					];
				}
				return new DataResponse($result);
			}

			// Thread markers (default)
			// Parse thread IDs from query parameter
			$threadIdArray = [];
			if (!empty($threadIds)) {
				$threadIdArray = array_map('intval', explode(',', $threadIds));
			}

			if (empty($threadIdArray)) {
				// Return all markers if no specific threads requested
				$markers = $this->readMarkerMapper->findByUserId($user->getUID());
				$result = [];
				foreach ($markers as $marker) {
					$result[$marker->getEntityId()] = [
						'entityId' => $marker->getEntityId(),
						'lastReadPostId' => $marker->getLastReadPostId(),
						'readAt' => $marker->getReadAt(),
					];
				}
				return new DataResponse($result);
			}

			$markers = $this->readMarkerMapper->findByUserAndThreads($user->getUID(), $threadIdArray);

			// Convert to associative array keyed by thread ID for easier frontend lookup
			$result = [];
			foreach ($markers as $marker) {
				$result[$marker->getEntityId()] = [
					'entityId' => $marker->getEntityId(),
					'lastReadPostId' => $marker->getLastReadPostId(),
					'readAt' => $marker->getReadAt(),
				];
			}

			return new DataResponse($result);
		} catch (\Exception $e) {
			$this->logger->error('Error fetching read markers: ' . $e->getMessage());
			return new DataResponse(['error' => 'Failed to fetch read markers'], Http::STATUS_INTERNAL_SERVER_ERROR);
		}
	}

	/**
	 * Get read marker for a specific thread
	 *
	 * @param int $threadId Thread ID
	 * @return DataResponse<Http::STATUS_OK, array<string, mixed>, array{}>
	 *
	 * 200: Read marker returned
	 */
	#[NoAdminRequired]
	#[ApiRoute(verb: 'GET', url: '/api/threads/{threadId}/read-marker')]
	public function show(int $threadId): DataResponse {
		try {
			$user = $this->userSession->getUser();
			if (!$user) {
				return new DataResponse(['error' => 'User not authenticated'], Http::STATUS_UNAUTHORIZED);
			}

			$marker = $this->readMarkerMapper->findByUserAndThread($user->getUID(), $threadId);
			return new DataResponse($marker->jsonSerialize());
		} catch (DoesNotExistException $e) {
			return new DataResponse(['error' => 'Read marker not found'], Http::STATUS_NOT_FOUND);
		} catch (\Exception $e) {
			$this->logger->error('Error fetching read marker: ' . $e->getMessage());
			return new DataResponse(['error' => 'Failed to fetch read marker'], Http::STATUS_INTERNAL_SERVER_ERROR);
		}
	}

	/**
	 * Mark a thread or category as read
	 *
	 * @param int $threadId Thread ID
	 * @param int $lastReadPostId Last read post ID
	 * @param int|null $categoryId Category ID (if provided, creates a category marker instead)
	 * @return DataResponse<Http::STATUS_OK, array<string, mixed>, array{}>
	 *
	 * 200: Marked as read
	 */
	#[NoAdminRequired]
	#[ApiRoute(verb: 'POST', url: '/api/read-markers')]
	public function create(int $threadId = 0, int $lastReadPostId = 0, ?int $categoryId = null): DataResponse {
		try {
			$user = $this->userSession->getUser();
			if (!$user) {
				return new DataResponse(['error' => 'User not authenticated'], Http::STATUS_UNAUTHORIZED);
			}

			// Category marker
			if ($categoryId !== null) {
				$marker = $this->readMarkerMapper->createOrUpdateCategoryMarker(
					$user->getUID(),
					$categoryId
				);
				return new DataResponse($marker->jsonSerialize());
			}

			// Thread marker (default)
			if ($threadId === 0 || $lastReadPostId === 0) {
				return new DataResponse(['error' => 'threadId and lastReadPostId are required'], Http::STATUS_BAD_REQUEST);
			}

			$marker = $this->readMarkerMapper->createOrUpdate(
				$user->getUID(),
				$threadId,
				$lastReadPostId
			);

			// Dismiss notifications if the user has caught up with the thread
			try {
				$this->notificationService->dismissNotificationsIfRead(
					$user->getUID(),
					$threadId,
					$lastReadPostId
				);
			} catch (\Exception $e) {
				$this->logger->warning('Failed to dismiss notifications: ' . $e->getMessage());
				// Don't fail the request if notification dismissal fails
			}

			return new DataResponse($marker->jsonSerialize());
		} catch (\Exception $e) {
			$this->logger->error('Error marking as read: ' . $e->getMessage());
			return new DataResponse(['error' => 'Failed to mark as read'], Http::STATUS_INTERNAL_SERVER_ERROR);
		}
	}

	/**
	 * Delete a read marker
	 *
	 * @param int $id Read marker ID
	 * @return DataResponse<Http::STATUS_OK, array{success: bool}, array{}>
	 *
	 * 200: Read marker deleted
	 */
	#[NoAdminRequired]
	#[ApiRoute(verb: 'DELETE', url: '/api/read-markers/{id}')]
	public function destroy(int $id): DataResponse {
		try {
			$marker = $this->readMarkerMapper->find($id);
			$this->readMarkerMapper->delete($marker);
			return new DataResponse(['success' => true]);
		} catch (DoesNotExistException $e) {
			return new DataResponse(['error' => 'Read marker not found'], Http::STATUS_NOT_FOUND);
		} catch (\Exception $e) {
			$this->logger->error('Error deleting read marker: ' . $e->getMessage());
			return new DataResponse(['error' => 'Failed to delete read marker'], Http::STATUS_INTERNAL_SERVER_ERROR);
		}
	}
}
