package de.htwsaar.webshop.service.impl;

import de.htwsaar.webshop.repository.AccountRepository;
import de.htwsaar.webshop.repository.CustomerRepository;
import de.htwsaar.webshop.repository.entities.Account;
import de.htwsaar.webshop.service.AccountService;
import de.htwsaar.webshop.service.PasswordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AccountServiceImpl implements AccountService {
    private final AccountRepository accountRepository;
    private final PasswordService passwordService;
    private final CustomerRepository customerRepository;

    @Autowired
    public AccountServiceImpl(AccountRepository accountRepository, PasswordService passwordService, CustomerRepository customerRepository) {
        this.accountRepository = accountRepository;
        this.passwordService = passwordService;
        this.customerRepository = customerRepository;
    }

    @Override
    public List<Account> findAll() {
        return accountRepository.findAll();
    }

    @Override
    public Account save(Account account) {
        return accountRepository.save(account);
    }

    @Override
    public Account saveNew(Account account) {
        if (account.getCustomer() != null) {
            account.getCustomer().setId(null); // Ensure new customer
            customerRepository.save(account.getCustomer());
        }
        account.setPassword(passwordService.hashPassword(account.getPassword()));
        return this.save(account);
    }

    @Override
    public boolean deleteIfExists(Account account) {
        Account tbd = accountRepository.getAccountByEmail(account.getEmail());
        if (tbd == null) {
            return false;
        }
        accountRepository.delete(tbd);
        return true;
    }

    @Override
    public Account isValidLogin(String email, String password) {
        Account acc = accountRepository.getAccountByEmail(email);
        if (acc == null) {
            return null;
        }
        return passwordService.verifyPassword(password, acc.getPassword()) ? acc : null;
    }

    @Override
    public boolean existsWithEmail(String email) {
        return accountRepository.existsAccountByEmail(email);
    }
}
