// otp.repository.ts

import { Injectable } from "@nestjs/common";

import { InjectRepository } from "@nestjs/typeorm";

import { Repository } from "typeorm";

import { OtpVerification } from "./otp.entity";

@Injectable()
export class OtpRepository {
  constructor(
    @InjectRepository(
      OtpVerification
    )
    private readonly repository: Repository<OtpVerification>
  ) {}

  // ---------------------------------------------------------------------------
  // Find By Phone
  // ---------------------------------------------------------------------------

  async findByPhone(
    phone: string
  ) {
    return this.repository.findOne({
      where: {
        phone,
      },
    });
  }

  // ---------------------------------------------------------------------------
  // Create OTP
  // ---------------------------------------------------------------------------

  async createOtp(
    phone: string,
    otp: string
  ) {
    const entity =
      this.repository.create({
        phone,
        otp,
        verified: false,
      });

    return this.repository.save(
      entity
    );
  }

  // ---------------------------------------------------------------------------
  // Update OTP
  // ---------------------------------------------------------------------------

  async updateOtp(
    otpVerification: OtpVerification,
    otp: string
  ) {
    otpVerification.otp = otp;

    otpVerification.verified =
      false;

    return this.repository.save(
      otpVerification
    );
  }

  // ---------------------------------------------------------------------------
  // Verify Phone
  // ---------------------------------------------------------------------------

  async verifyPhone(
    otpVerification: OtpVerification
  ) {
    otpVerification.verified =
      true;

    return this.repository.save(
      otpVerification
    );
  }
}