import { Inject, Injectable } from "@nestjs/common";
import { AccountRepo } from "./account.repo";
import * as DTO from './dto';
import { MailerService } from "src/util/mailer/mailer.service";
import { Generator } from "src/util/generator";
import Redis from "ioredis";
import { Converter } from "src/util/converter";

@Injectable()
export class AccountService {
  constructor(
    private readonly accountRepo: AccountRepo
    , private readonly mailerService: MailerService
    , @Inject("REDIS") private readonly redis: Redis
  ) {}

  async checkDuplication(data: DTO.CheckDuplicationRequest): Promise<DTO.CheckDuplicationResponse> {
    const { type, value } = data;
    const count = await this.accountRepo.checkDuplication(type, value);

    return { isDuplicated: count > 0 };
  }

  async sendVerificationCode(data: DTO.SendVerificationCodeRequest): Promise<DTO.SendVerificationCodeResponse> {
    const { email } = data;
    const code = Generator.getVerificationCode();
    const html = `<p>Your verification code is: <strong style="font-size:16px;">${code}</strong></p>`;
    const result = await this.mailerService.sendMail(email, "<Scheduler> 이메일 인증 코드", html);

    if (result.rejected.length > 0) {
      return { success: false, error: result.response }
    } else {
      await this.redis.set(`verify:${email}`, code, 'EX', 600);

      return { success: true, message: "이메일 발송 완료" };
    }
  }

  async verifyCode(data: DTO.VerifyCodeRequest): Promise<DTO.VerifyCodeResponse> {
    const { email, code } = data;

    const storedCode = await this.redis.get(`verify:${email}`);

    if (!storedCode) {
      return { verified: false, error: '잘못된 이메일이거나 코드가 만료되었습니다.'};
    }
    if (storedCode !== code) {
      return { verified: false, error: "잘못된 코드입니다." };
    }

    await this.redis.del(`verify:${email}`);
    return { verified: true, message: "이메일 인증이 완료되었습니다." };
  }

  async signup(data: DTO.SignupRequest): Promise<DTO.SignupResponse> {
    const { accountId, name, nickname, email, password } = data;
    const hashedPassword = Converter.getHashedPassword(password);
    const result = await this.accountRepo.signup(accountId, name, nickname, email, hashedPassword);

    if (result.rowCount) {
      return {
        success: true,
        message: "회원가입이 완료되었습니다."
      };
    } else {
      return {
        success: false,
        error: "회원가입에 실패하였습니다."
      };
    }
    
  }
}