// IMPORT LIBRARY
import { Service } from "@tsed/common";

// IMPORT CUSTOM
import { CoreService } from "../core/services/CoreService";
import { BadRequest } from "ts-httpexceptions";
import { Customer } from "../entity/Customer";

@Service()
export class CustomerService extends CoreService {

    // =====================LOGIN=====================
    public async login(phone: string, password: string): Promise<Customer> {
        const customer = await Customer.findOneOrThrowOption({
            select: ['password'],
            where: { phone }
        })

        const isValidPass = await customer.isValidPassword(password)
        if (!isValidPass) {
            throw new BadRequest('Tài khoản hoặc mật khẩu không đúng! Vui lòng thử lại')
        }

        if (customer.isBlock) {
            throw new BadRequest('Tài khoản này đã bị khoá!')
        }

        return customer
    }


    // =====================CHECK DUPLICATE=====================
    async checkDuplicate(customer: Customer, userId: number = null) {
        const { phone, email } = customer

        const oldCustomer = await Customer.findOne({
            where: [
                { phone },
                { email }
            ]
        })

        if (oldCustomer && oldCustomer.id != userId) {
            let message = ""

            if (oldCustomer.phone == phone) {
                message = "Số điện thoại"
            } else if (oldCustomer.email == email) {
                message = "Email"
            }

            throw new BadRequest(`${message} đã tồn tại`)
        }
    }


} // END FILE
