import { ValidationError } from '../lib/validation';

export const LOGIN_ERROR = 'LOGIN_ERROR';
export const LOGIN_START = 'LOGIN_START';
export const LOGIN_SUCCESS = 'LOGIN_SUCCESS';
export const LOGOUT = 'LOGOUT';

export function login(fields) {
  return ({ fetch, validate }) => {
    const getPromise = async () => {
      try {
        await validate(fields)
          .prop('email').required().email()
          .prop('password').required().simplePassword()
          .promise;
        // Sure we can use smarter api than raw fetch.
        const response = await fetch('/api/v1/auth/login', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(fields)
        });
        if (response.status !== 200) throw response;
        // Return JSON response.
        return response.json();
      } catch (error) {
        // Transform error status to custom error.
        if (error.status === 401) {
          throw new ValidationError('wrongPassword', { prop: 'password' });
        }
        if (error.status === 404) {
          throw new ValidationError('notFound', { prop: 'password' });
        }
        throw error;
      }
    };

    return {
      type: 'LOGIN',
      payload: {
        promise: getPromise()
      }
    };
  };
}

@@ -474,24 +474,240 @@
   .promise;%0A
+        // Simulate response for server-less (Firebase hosting) example.%0A        if (process.env.IS_SERVERLESS) %7B%0A          return %7B%0A            email: fields.email,%0A            id: Date.now()%0A          %7D;%0A        %7D%0A
         // S

Fix XHR login on Firebase hosting