import {
  adapters,
  migrationFields,
  newUuid,
} from '@/services/serviceConfig';

import { auditService } from '@/services/auditService';

const workflowFor = (data, limb) => {
  const interfaceType =
    data.interface_type
    || limb?.interface_type
    || '';

  const limbRegion =
    data.limb_region
    || limb?.limb_region
    || '';

  const level =
    data.amputation_level
    || limb?.amputation_level
    || limb?.configuration
    || '';

  if (interfaceType === 'Osseointegration') {
    return 'Osseointegration';
  }

  if (
    limbRegion === 'Upper limb'
    || /elbow|wrist|shoulder/i.test(level)
  ) {
    return 'Upper limb';
  }

  if (
    /above-knee|knee disarticulation|hip disarticulation/i.test(
      level
    )
  ) {
    return 'Knee component';
  }

  return 'Lower leg';
};

export const projectService = {
  list: () =>
    adapters.database.list('CoverProject'),

  get: async uuid =>
    (
      await adapters.database.filter(
        'CoverProject',
        { uuid },
        '-updated_date',
        1
      )
    )[0],

  filter: query =>
    adapters.database.filter(
      'CoverProject',
      query
    ),

  async create(data, actor) {
    const {
      id,
      created_date,
      updated_date,
      created_by_id,
      ...portable
    } = data;

    const uuid = newUuid('proj');

    const record =
      await adapters.database.create(
        'CoverProject',
        {
          ...portable,
          uuid,
          project_id:
            `SLC-${new Date().getFullYear()}-${Date.now()
              .toString()
              .slice(-5)}`,
          revision: 1,
          storage_destination:
            `/SHiREVault/SHiRELimbs/Projects/${uuid}`,
          safety_boundary_accepted: true,
          component_verification_status:
            data.components_pending
              ? 'Unknown - add and verify before manufacturing'
              : (
                  data.component_verification_status
                  || 'Selected - verification required'
                ),
          manufacturing_release_blocked:
            data.components_pending === true,
          manufacturing_release_reason:
            data.components_pending
              ? 'Receiving prosthetic components and approved external attachment regions are not yet verified.'
              : '',
          ...migrationFields(actor),
          revision: data.revision || 1,
        }
      );

    if (
      data.measurement_method?.includes('Manual')
      || data.measurement_method?.includes(
        'Combination'
      )
    ) {
      const limb =
        (
          await adapters.database.filter(
            'LimbProfile',
            {
              uuid: data.limb_profile_uuid,
            },
            '-updated_date',
            1
          )
        )[0];

      const workflow = workflowFor(
        data,
        limb
      );

      await adapters.database.create(
        'MeasurementSession',
        {
          uuid: newUuid('session'),
          project_uuid: uuid,
          customer_uuid: data.customer_uuid,
          limb_profile_uuid:
            data.limb_profile_uuid,
          workflow,
          status: 'Not started',
          measured_by: actor,
          measured_date:
            new Date()
              .toISOString()
              .slice(0, 10),
          progress_percent: 0,
          ...migrationFields(actor),
        }
      );
    }

    await auditService.record(
      'project_created',
      'CoverProject',
      uuid,
      `Created cover project ${record.project_id}`,
      actor,
      data.components_pending
        ? 'Non-load-bearing cosmetic cover only. Component details remain unverified and manufacturing release is blocked.'
        : 'Non-load-bearing cosmetic prosthetic cover only. Manual review required.'
    );

    return record;
  },

  duplicate: async (project, actor) =>
    projectService.create(
      {
        ...project,
        id: undefined,
        project_id: undefined,
        revision: project.revision + 1,
        status: 'Awaiting measurements',
        reason_for_cover:
          `Revision of ${project.project_id}`,
      },
      actor
    ),

  archive: async (
    record,
    actor = 'Ray'
  ) => {
    await adapters.database.archive(
      'CoverProject',
      record.id
    );

    return auditService.record(
      'project_archived',
      'CoverProject',
      record.uuid,
      `Archived ${record.project_id}`,
      actor
    );
  },

  restore: async (
    record,
    actor = 'Ray'
  ) => {
    await adapters.database.restore(
      'CoverProject',
      record.id
    );

    return auditService.record(
      'project_restored',
      'CoverProject',
      record.uuid,
      `Restored ${record.project_id}`,
      actor
    );
  },
};
