import { Inject, Injectable } from "@nestjs/common";
import * as schema from "drizzle/schema";
import { countDistinct, and, eq, not } from 'drizzle-orm';
import { NodePgDatabase } from "drizzle-orm/node-postgres";

@Injectable()
export class AccountRepo {
  constructor(@Inject('DRIZZLE') private readonly db: NodePgDatabase<typeof schema>) {}

  async checkIdExists(type: 'email' | 'accountId', value: string) {
    const result = await this
    .db
    .select({ count: countDistinct(schema.account[type])})
    .from(schema.account)
    .where(
      eq(schema.account[type], value)
    );

    return result[0].count;
  }

  async signup(
    accountId: string,
    name: string,
    nickname: string,
    email: string,
    password: string
  ) {
    return await this
    .db
    .insert(schema.account)
    .values({
      accountId: accountId,
      name: name,
      nickname: nickname,
      email: email,
      password: password
    });
  }

  async login(
    type: 'email' | 'accountId'
    , id: string
  ) {
    return await this
    .db
    .select()
    .from(schema.account)
    .where(
      and(
        eq(schema.account[type], id),
        eq(schema.account.isDeleted, false),
        eq(schema.account.status, 'active')
      )
    );
  }

  async findById(id: string) {
    return await this
    .db
    .select()
    .from(schema.account)
    .where(
      and(
        eq(schema.account.id, id),
        eq(schema.account.isDeleted, false)
      )
    )
  }

  async updatePassword(type: 'email' | 'accountId', id: string, value: string) {
    return await this
    .db
    .update(schema.account)
    .set({
      password: value
    })
    .where(
      and(
        eq(schema.account[type], id),
        eq(schema.account.isDeleted, false)
      )
    );
  }
}