import { Follower } from "../api/followers/models"
import { MutualFollow } from "../api/mutual-follows/models"
import { User } from "../api/users/models"

async function execute() {
  const users = JSON.parse(JSON.stringify(await User.find({}, {_id: 1, username: 1}).lean()))
  const followers = JSON.parse(JSON.stringify(await Follower.find({}, {follower: 1, following: 1}).lean()))
  let pairs: Record<string, boolean>[] = []
  for(let follower of followers) {
    const match = followers.find((e: any) => e.follower === follower.following && e.following === follower.follower)
    if(match) {
      const u1 = users.find((e: any) => e._id === match.follower)
      const u2 = users.find((e: any) => e._id === match.following)
      if(pairs.some(e => e[u1.username] && e[u2.username])) {
        continue
      }
      pairs.push({[u1.username]: true, [u2.username]: true})
      console.log(u1.username, u2.username)
      await MutualFollow.create({ users: [u1._id, u2._id] })
    }
  }
}

const scriptCreateMutualFollows = {
  execute
}

export default scriptCreateMutualFollows