import clickTtAccountService from '../services/clickTtAccountService.js';
import HttpError from '../exceptions/HttpError.js';

class ClickTtAccountController {
  async getAccount(req, res, next) {
    try {
      const account = await clickTtAccountService.getAccount(req.user.id);
      res.status(200).json({ account });
    } catch (error) {
      next(error);
    }
  }

  async getStatus(req, res, next) {
    try {
      const status = await clickTtAccountService.checkAccountStatus(req.user.id);
      res.status(200).json(status);
    } catch (error) {
      next(error);
    }
  }

  async upsertAccount(req, res, next) {
    try {
      const { username, password, savePassword, userPassword } = req.body;
      if (!username) {
        throw new HttpError('Benutzername erforderlich', 400);
      }
      if (password && !userPassword) {
        throw new HttpError('App-Passwort erforderlich zum Setzen des HTTV-/click-TT-Passworts', 400);
      }

      const account = await clickTtAccountService.upsertAccount(
        req.user.id,
        username,
        password,
        savePassword || false,
        userPassword
      );

      res.status(200).json({
        message: 'HTTV-/click-TT-Account erfolgreich gespeichert',
        account
      });
    } catch (error) {
      next(error);
    }
  }

  async deleteAccount(req, res, next) {
    try {
      const deleted = await clickTtAccountService.deleteAccount(req.user.id);
      if (!deleted) {
        throw new HttpError('Kein HTTV-/click-TT-Account gefunden', 404);
      }
      res.status(200).json({ message: 'HTTV-/click-TT-Account gelöscht' });
    } catch (error) {
      next(error);
    }
  }

  async verifyLogin(req, res, next) {
    try {
      const result = await clickTtAccountService.verifyLogin(req.user.id, req.body.password);
      res.status(200).json({ success: true, message: 'Login erfolgreich', ...result });
    } catch (error) {
      next(error);
    }
  }
}

export default new ClickTtAccountController();
