import { Injectable, CanActivate, ExecutionContext, ForbiddenException, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { GroupMember, GroupRole } from '@/entities/group-member.entity';

@Injectable()
export class GroupRemoveMemberGuard implements CanActivate {
  constructor(
    @InjectRepository(GroupMember)
    private groupMemberRepo: Repository<GroupMember>,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const req = context.switchToHttp().getRequest();
    const user = req.user;
    if (!user) return false;

    const groupId = req.params?.id;
    const targetUserId = req.params?.userId;
    if (!groupId || !targetUserId) return false;

    const target = await this.groupMemberRepo.findOne({ where: { group: { id: groupId }, user: { id: targetUserId } } });
    if (!target) throw new NotFoundException('Member not found');

    // if target is owner, disallow removal via this route
    if (target.role === GroupRole.OWNER) {
      if (targetUserId === user.id) {
        throw new BadRequestException('Owner cannot remove themselves. Transfer ownership or delete group.');
      }
      throw new ForbiddenException('Cannot remove owner');
    }

    // if requester is the same user -> allow removing self
    if (user.id === targetUserId) return true;

    // otherwise requester must be owner or admin
    const requester = await this.groupMemberRepo.findOne({ where: { group: { id: groupId }, user: { id: user.id } } });
    if (!requester || (requester.role !== GroupRole.OWNER && requester.role !== GroupRole.ADMIN)) {
      throw new ForbiddenException('Only owner or admin can remove members');
    }

    return true;
  }
}
