import { Q } from '@nozbe/watermelondb';
import { database } from 'src/watermelondb';
import BlockedUser from 'src/watermelondb/models/BlockedUser';

type Blocked = {
  id: number;
  first_name: string;
  last_name: string;
  avatar: string | null;
};

export async function upsertBlockedUsers(users: Blocked[]) {
  if (!users?.length) return;
  const collection = database.get<BlockedUser>('blocked_users');

  await database.write(async () => {
    const batch: any[] = [];

    for (const u of users) {
      const existingNow = await collection.query(Q.where('user_id', u.id)).fetch();

      if (existingNow.length) {
        batch.push(
          existingNow[0].prepareUpdate((rec) => {
            rec.firstName = u.first_name;
            rec.lastName = u.last_name;
            rec.avatar = u.avatar ?? null;
            rec.removed = false;
          })
        );
      } else {
        batch.push(
          collection.prepareCreate((rec) => {
            rec.userId = u.id;
            rec.firstName = u.first_name;
            rec.lastName = u.last_name;
            rec.avatar = u.avatar ?? null;
            rec.removed = false;
          })
        );
      }
    }

    await database.batch(batch);
  });
}
