import { Connection } from 'typeorm';
import { decodeBigNumberKey } from '../utils/big-number-key';
import { ActualProjectLicenseEntity } from '../entities/actual-project-license.entity';
import { ProjectLicense } from '../asset/logic/ProjectLicense';

export const LICENSE_EXPIRATION_DELAY_HOURS = 8;

const MB = 1024 * 1024;

export function getDefaultLicense(): ProjectLicense {
  return {
    id: 0,
    title: '[[t:LicenseTypeFree]]',
    name: 'free',
    startAt: null,
    till: null,
    isTrial: false,
    features: {
      apiAccess: false,
      fsMaxFileSize: 10 * MB,
      fsStorageSize: 1024 * MB,
      gmBuildSize: 5368709120,
      maxAssets: 500,
      maxMembers: 5,
      roleSettings: false,
      taskCalendar: false,
      taskTimeTracking: false,
      customTaskBoards: false,
      communityPublication: false,
      communityShortLink: false,
      communityStatistics: false,
      exportProject: false,
      importProject: true,
    },
  };
}

export async function getProjectLicense(
  connection: Connection,
  projectId: string,
): Promise<ProjectLicense> {
  const def = getDefaultLicense();
  const project_license = await connection
    .createQueryBuilder()
    .from(ActualProjectLicenseEntity, 'apl')
    .where('apl.project_id = :projectId', {
      projectId: decodeBigNumberKey(projectId),
    })
    .select([
      'apl.license_type_name as name',
      'apl.license_type_title as title',
      'apl.id as id',
      'apl.start_at as start_at',
      'apl.till as till',
      'apl.is_trial as is_trial',
      'apl.features as project_license_features',
      'apl.license_type_features as license_type_features',
    ])
    .getRawOne();
  if (!project_license) {
    return def;
  }

  const res: ProjectLicense = {
    id: project_license.id,
    features: {
      ...def.features,
      ...project_license.license_type_features,
      ...(project_license.project_license_features
        ? project_license.project_license_features
        : {}),
    },
    isTrial: !!project_license.is_trial,
    name: project_license.name,
    title: project_license.title,
    startAt: new Date(project_license.start_at),
    till: project_license.till ? new Date(project_license.till) : null,
  };

  return res;
}
