const TENANT_LICENSES_DDL = `
  CREATE TABLE IF NOT EXISTS tenant_licenses (
    id TEXT PRIMARY KEY,
    tenant_id TEXT NOT NULL,
    term_name TEXT NOT NULL,
    academic_year TEXT NOT NULL,
    start_date TEXT NOT NULL,
    end_date TEXT NOT NULL,
    grace_period_days INTEGER DEFAULT 7,
    max_students INTEGER DEFAULT 1000,
    max_staff INTEGER DEFAULT 200,
    license_key TEXT NOT NULL,
    signed_license_token TEXT NOT NULL,
    algorithm TEXT DEFAULT 'EdDSA',
    status TEXT DEFAULT 'ACTIVE',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  );
`;

exports.up = async function (knex) {
  const hasTable = await knex.schema.hasTable('tenant_licenses');
  if (!hasTable) {
    await knex.schema.raw(TENANT_LICENSES_DDL);
    return;
  }

  const hasSignedToken = await knex.schema.hasColumn('tenant_licenses', 'signed_license_token');
  if (!hasSignedToken) {
    await knex.schema.alterTable('tenant_licenses', (table) => {
      table.text('signed_license_token');
    });
  }

  const hasAlgorithm = await knex.schema.hasColumn('tenant_licenses', 'algorithm');
  if (!hasAlgorithm) {
    await knex.schema.alterTable('tenant_licenses', (table) => {
      table.text('algorithm').defaultTo('EdDSA');
    });
  }
};

exports.down = async function (knex) {
  const hasTable = await knex.schema.hasTable('tenant_licenses');
  if (!hasTable) return;

  if (await knex.schema.hasColumn('tenant_licenses', 'algorithm')) {
    await knex.schema.alterTable('tenant_licenses', (table) => {
      table.dropColumn('algorithm');
    });
  }

  if (await knex.schema.hasColumn('tenant_licenses', 'signed_license_token')) {
    await knex.schema.alterTable('tenant_licenses', (table) => {
      table.dropColumn('signed_license_token');
    });
  }
};
