///<reference types="cypress" />

function submitLogin(){
  const userAttrs = {
    id: '1',
    first_name: 'Peter',
    last_name: 'Pan',
    name: 'Peter Pan',
    photo_url: '',
    email: 'peter@example.com'
  }

  cy.intercept('POST', `${Cypress.env('apiBaseUrl')}/auths/login`, {
    statusCode: 200,
    body: userAttrs
  }).as('createSession')

  cy.intercept('GET', `${Cypress.env('apiBaseUrl')}/me`, {
    statusCode: 200,
    body: userAttrs
  }).as('getCurrentUser')

  cy.reload()
  cy.get('[data-testid=email]').type('peter@example.com')
  cy.get('[data-testid=password]').type('jam123')
  cy.get('[data-testid=submit]').click()
  
}

describe('Unauthenticated users redirect to login page', () => {
  it('redirects to login page', () => {
    cy.clearCookie('remeber_token')
    cy.visit('/')
    cy.url().should('include', '/auth/login')
    cy.contains('Sign In')
  })
})

describe('Login page', () => {
  before(() => {
    cy.clearCookie('remeber_token')
  })
  
  it('validate login form', () => {
    cy.visit('/auth/login')
    cy.reload()
    cy.get('[data-testid=submit]').should('be.disabled')
    cy.get('[data-testid=email]').type('invalid-email-format@example')
    cy.get('[data-testid=submit]').should('be.disabled')
    cy.get('[data-testid=email]').type('valid-email-format@example.com')
    cy.get('[data-testid=submit]').should('be.disabled')
    cy.get('[data-testid=password]').type('password')
    cy.get('[data-testid=submit]').should('not.be.disabled')
  })

  it('submit login form with invalid credentials', () => {
    cy.visit('/auth/login')
    cy.reload()
    cy.get('[data-testid=email]').type('peter@example.com')
    cy.get('[data-testid=password]').type('wrong')
    cy.get('[data-testid=submit]').click()
    cy.contains('Incorrect email or password')
  })

  it('submits login form', () => {
    cy.visit('/auth/login')
    submitLogin()
    cy.url().should('eq', Cypress.config().baseUrl + '/') // tests won't fail in case the port changes
    //cy.contains('Signed in as peter@example.com')
    //cy.contains('Peter Pan')
    //cy.getCookie('remember_token').should('exist')
  })

  it('redirect to requested page', () => {
    cy.visit('/friends')
    cy.url().should('include', '/auth/login')
    cy.reload()
    submitLogin()
    cy.url().should('eq', Cypress.config().baseUrl + '/friends')
  })
    
})

describe('Forget password page', () => {
  it('submit forget password form', () => {
    cy.visit('/auth/forget-password')
    cy.get('[data-testid=email]').type('peter@example.com')
    cy.get('[data-testid=submit]').click()
    cy.contains('An email is sent')
  })
})


