import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { Types } from 'mongoose';
import { PaginationQueryDto } from '../../common/dto/pagination-query.dto';
import { buildPaginatedResponse } from '../../common/utils/pagination.util';
import { resolveMongoSortDirection } from '../../common/utils/sort.util';
import { FeedVersionService } from '../../infrastructure/cache/feed-version.service';
import { NotificationsService } from '../notifications/notifications.service';
import { PostsRepository } from '../posts/posts.repository';
import { ToggleSaveDto } from './dto/toggle-save.dto';
import { SavesRepository } from './saves.repository';

@Injectable()
export class SavesService {
  private readonly logger = new Logger(SavesService.name);

  constructor(
    private readonly savesRepository: SavesRepository,
    private readonly postsRepository: PostsRepository,
    private readonly feedVersionService: FeedVersionService,
    private readonly notificationsService: NotificationsService,
  ) {}

  async toggle(userId: string, dto: ToggleSaveDto): Promise<{ saved: boolean; postId: string }> {
    const existing = await this.savesRepository.findOne(userId, dto.postId);
    return existing ? this.unsave(userId, dto) : this.save(userId, dto);
  }

  async save(userId: string, dto: ToggleSaveDto): Promise<{ saved: boolean; postId: string }> {
    const post = await this.getPostOrThrow(dto.postId);

    const existing = await this.savesRepository.findOne(userId, dto.postId);
    if (existing) {
      return { saved: true, postId: dto.postId };
    }

    await this.savesRepository.create(userId, dto.postId);
    await this.postsRepository.incrementSavesCount(dto.postId, 1);
    await this.feedVersionService.bumpGlobalVersion();
    const recipientId = this.extractEntityId(post.authorId);
    if (recipientId && recipientId !== userId) {
      try {
        await this.notificationsService.createSaveNotification(userId, recipientId, dto.postId, {
          resourceType: 'post',
          previewText: (post.content ?? '').slice(0, 140),
        });
      } catch (error) {
        this.logger.warn(
          `Save notification failed for actor=${userId} recipient=${recipientId}: ${
            error instanceof Error ? error.message : 'unknown error'
          }`,
        );
      }
    }
    return { saved: true, postId: dto.postId };
  }

  async unsave(userId: string, dto: ToggleSaveDto): Promise<{ saved: boolean; postId: string }> {
    await this.assertPostExists(dto.postId);

    const existing = await this.savesRepository.findOne(userId, dto.postId);
    if (!existing) {
      return { saved: false, postId: dto.postId };
    }

    await this.savesRepository.deleteById(existing.id);
    await this.postsRepository.incrementSavesCount(dto.postId, -1);
    await this.feedVersionService.bumpGlobalVersion();
    return { saved: false, postId: dto.postId };
  }

  async getStatus(userId: string, dto: ToggleSaveDto): Promise<{ saved: boolean; postId: string }> {
    const postExists = await this.postExists(dto.postId);
    if (!postExists) {
      return { saved: false, postId: dto.postId };
    }

    const existing = await this.savesRepository.findOne(userId, dto.postId);
    return { saved: !!existing, postId: dto.postId };
  }

  async getMySavedPosts(userId: string, query: PaginationQueryDto) {
    const page = query.page ?? 1;
    const limit = query.limit ?? 20;
    const skip = (page - 1) * limit;
    const sort = { createdAt: resolveMongoSortDirection(query.sortOrder) } as Record<string, 1 | -1>;

    const [postIds, total] = await Promise.all([
      this.savesRepository.findUserSavedPostIds(userId, skip, limit, sort),
      this.savesRepository.countByUser(userId),
    ]);

    const items = await this.postsRepository.findManyByIds(postIds);

    return buildPaginatedResponse(items, {
      page,
      limit,
      total,
      offset: skip,
    });
  }

  private async assertPostExists(postId: string): Promise<void> {
    await this.getPostOrThrow(postId);
  }

  private async postExists(postId: string): Promise<boolean> {
    const post = await this.postsRepository.findById(postId);
    return !!post;
  }

  private async getPostOrThrow(postId: string) {
    const post = await this.postsRepository.findById(postId);
    if (!post) {
      throw new NotFoundException('Post not found');
    }
    return post;
  }

  private extractEntityId(value: unknown): string {
    if (!value) {
      return '';
    }

    if (typeof value === 'string') {
      return value;
    }

    if (value instanceof Types.ObjectId) {
      return value.toString();
    }

    if (typeof value === 'object') {
      const candidate = value as { _id?: unknown; id?: unknown };
      if (candidate._id instanceof Types.ObjectId) {
        return candidate._id.toString();
      }
      if (typeof candidate._id === 'string') {
        return candidate._id;
      }
      if (typeof candidate.id === 'string') {
        return candidate.id;
      }
    }

    return '';
  }
}
