const config = require('../../../knexfile').extweb
const knex = require('knex')(config)
const AboutYou = require('../domain/about-you')

module.exports = function (reference, eligibilityId, aboutYou) {
  if (!(aboutYou instanceof AboutYou)) {
    throw new Error('Provided aboutYou object is not an instance of the expected class')
  }

  var dateOfBirth = aboutYou.dob.toDate()

  return knex('Visitor').insert({
    EligibilityId: eligibilityId,
    Reference: reference,
    FirstName: aboutYou.firstName,
    LastName: aboutYou.lastName,
    NationalInsuranceNumber: aboutYou.nationalInsuranceNumber,
    HouseNumberAndStreet: aboutYou.houseNumberAndStreet,
    Town: aboutYou.town,
    County: aboutYou.county,
    PostCode: aboutYou.postCode,
    Country: aboutYou.country,
    EmailAddress: aboutYou.emailAddress,
    PhoneNumber: aboutYou.phoneNumber,
    DateOfBirth: dateOfBirth,
    Relationship: aboutYou.relationship,
    Benefit: aboutYou.benefit
  })
}

@@ -379,38 +379,33 @@
 %0A%0A  
-return knex('Visitor').insert(
+var visitorInformation = 
 %7B%0A  
@@ -949,15 +949,404 @@
 benefit%0A
+  %7D%0A%0A  return knex('Eligibility')%0A  .where('Reference', reference)%0A  .count('Reference as ReferenceCount')%0A  .then(function (countResult) %7B%0A    var count = countResult%5B 0 %5D.ReferenceCount%0A%0A    if(count===0)%7B%0A      return knex('Visitor')%0A      .insert(visitorInformation)%0A    %7D else %7B%0A      return knex('Visitor')%0A      .where('Reference',reference)%0A      .update(visitorInformation)%0A    %7D%0A
   %7D)%0A%7D%0A

Modify insert-visitor.js to update any exisiting visitor details for given reference.