'use strict';

const { makeExtendSchemaPlugin, gql } = require('graphile-utils');
const moment = require('moment');
const { cmToFeetInches, kgToLbs } = require('../../utils/convert');

const schemaExtender = makeExtendSchemaPlugin(_build => ({
    typeDefs: gql`
        enum Units {
            METRIC
            IMPERIAL
        }

      extend type Actor {
        age: Int @requires(columns: ["birthdate"])
        height(units:Units): String @requires(columns: ["height"])
        weight(units:Units): String @requires(columns: ["weight"])
      }
    `,
    resolvers: {
        Actor: {
            age(parent, _args, _context, _info) {
                if (!parent.birthdate) return null;

                return moment().diff(parent.birthdate, 'years');
            },
            height(parent, args, _context, _info) {
                if (!parent.height) return null;

                if (args.units === 'IMPERIAL') {
                    const { feet, inches } = cmToFeetInches(parent.height);
                    return `${feet}' ${inches}"`;
                }

                return parent.height.toString();
            },
            weight(parent, args, _context, _info) {
                if (!parent.weight) return null;

                return args.units === 'IMPERIAL'
                    ? kgToLbs(parent.weight).toString()
                    : parent.weight.toString();
            },
        },
    },
}));

module.exports = [schemaExtender];
