namespace Hims.Domain.Entities
{
    /// <summary>
    /// The accounts credential query model.
    /// </summary>
    public class AccountsCredential
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="AccountsCredential"/> class.
        /// </summary>
        /// <param name="account">
        /// The account.
        /// </param>
        /// <param name="passwordHash">
        /// The password hash.
        /// </param>
        public AccountsCredential(Account account, string passwordHash)
        {
            string query;
            if (string.IsNullOrEmpty(account.Mobile))
            {
                query = $@"UPDATE ""AccountCredential"" ac SET ""Active"" = FALSE FROM ""Account"" act
                        WHERE act.""AccountId"" = ac.""AccountId"" AND act.""Email"" = '{account.Email}';
                        INSERT INTO ""AccountCredential""(""AccountId"", ""PasswordHash"", ""CreatedBy"", ""CreatedDate"")
                        SELECT act.""AccountId"", '{passwordHash}', act.""AccountId"", NOW() AT TIME ZONE 'UTC' FROM ""Account"" act
                        WHERE act.""Email"" = '{account.Email}';";
            }
            else if (string.IsNullOrEmpty(account.Email))
            {
                query = $@"UPDATE ""AccountCredential"" ac SET ""Active"" = FALSE FROM ""Account"" act
                        WHERE act.""AccountId"" = ac.""AccountId"" AND act.""Mobile"" = '{account.Mobile}' AND act.""CountryId"" = '{account.CountryId}';
                        INSERT INTO ""AccountCredential""(""AccountId"", ""PasswordHash"", ""CreatedBy"", ""CreatedDate"")
                        SELECT act.""AccountId"", '{passwordHash}', act.""AccountId"", NOW() AT TIME ZONE 'UTC' FROM ""Account"" act
                        WHERE act.""Mobile"" = '{account.Mobile}' AND act.""CountryId"" = '{account.CountryId}';";
            }
            else
            {
                query = $@"UPDATE ""AccountCredential"" ac SET ""Active"" = FALSE FROM ""Account"" act
                        WHERE act.""AccountId"" = ac.""AccountId"" AND act.""Email"" = '{account.Email}' AND act.""Mobile"" = '{account.Mobile}' AND act.""CountryId"" = '{account.CountryId}';
                        INSERT INTO ""AccountCredential""(""AccountId"", ""PasswordHash"", ""CreatedBy"", ""CreatedDate"")
                        SELECT act.""AccountId"", '{passwordHash}', act.""AccountId"", NOW() AT TIME ZONE 'UTC' FROM ""Account"" act
                        WHERE act.""Email"" = '{account.Email}' AND act.""Mobile"" = '{account.Mobile}' AND act.""CountryId"" = '{account.CountryId}';";
            }

            this.Query = query;
        }

        /// <summary>
        /// Gets or sets the query.
        /// </summary>
        public string Query { get; set; }
    }
}