import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import {
  SyncedLegacyUserRepository,
  SyncedLegacyUserData,
  AccountSequence,
  Phone,
} from '@/domain';

@Injectable()
export class PrismaSyncedLegacyUserRepository implements SyncedLegacyUserRepository {
  constructor(private readonly prisma: PrismaService) {}

  async findByPhone(phone: Phone): Promise<SyncedLegacyUserData | null> {
    const user = await this.prisma.syncedLegacyUser.findFirst({
      where: { phone: phone.value },
    });

    if (!user) return null;
    return this.toDomain(user);
  }

  async findByAccountSequence(accountSequence: AccountSequence): Promise<SyncedLegacyUserData | null> {
    const user = await this.prisma.syncedLegacyUser.findUnique({
      where: { accountSequence: accountSequence.value },
    });

    if (!user) return null;
    return this.toDomain(user);
  }

  async markAsMigrated(accountSequence: AccountSequence): Promise<void> {
    await this.prisma.syncedLegacyUser.update({
      where: { accountSequence: accountSequence.value },
      data: {
        migratedToV2: true,
        migratedAt: new Date(),
      },
    });
  }

  async isMigrated(accountSequence: AccountSequence): Promise<boolean> {
    const user = await this.prisma.syncedLegacyUser.findUnique({
      where: { accountSequence: accountSequence.value },
      select: { migratedToV2: true },
    });

    return user?.migratedToV2 ?? false;
  }

  private toDomain(user: any): SyncedLegacyUserData {
    return {
      id: user.id,
      legacyId: user.legacyId,
      accountSequence: AccountSequence.create(user.accountSequence),
      phone: Phone.create(user.phone),
      passwordHash: user.passwordHash,
      nickname: user.nickname,
      status: user.status,
      legacyCreatedAt: user.legacyCreatedAt,
      migratedToV2: user.migratedToV2,
      migratedAt: user.migratedAt,
      syncedAt: user.syncedAt,
    };
  }
}
