import * as Sequelize from 'sequelize'

async function up (utils: {
  transaction: Sequelize.Transaction
  queryInterface: Sequelize.QueryInterface
  sequelize: Sequelize.Sequelize
}): Promise<void> {
  const query = `
    CREATE TABLE IF NOT EXISTS "liveVideo" (
      "id" SERIAL PRIMARY KEY,
      "title" VARCHAR(255) NOT NULL,
      "thumbnailFilename" VARCHAR(255),
      "videoOriginalName" VARCHAR(255) NOT NULL,
      "videoStoragePath" TEXT NOT NULL,
      "videoMimeType" VARCHAR(255) NOT NULL,
      "videoSize" BIGINT NOT NULL,
      "startTime" TIMESTAMP WITH TIME ZONE NOT NULL,
      "endTime" TIMESTAMP WITH TIME ZONE NOT NULL,
      "targetCamera" VARCHAR(255) NOT NULL,
      "status" VARCHAR(50) NOT NULL DEFAULT 'scheduled',
      "createdByUserId" INTEGER NOT NULL REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
      "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL,
      "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL
    )
  `

  await utils.sequelize.query(query, { transaction: utils.transaction })

  await utils.sequelize.query(
    `CREATE INDEX "idx_live_video_target_camera" ON "liveVideo" ("targetCamera")`,
    { transaction: utils.transaction }
  )

  await utils.sequelize.query(
    `CREATE INDEX "idx_live_video_start_time" ON "liveVideo" ("startTime")`,
    { transaction: utils.transaction }
  )

  await utils.sequelize.query(
    `CREATE INDEX "idx_live_video_status" ON "liveVideo" ("status")`,
    { transaction: utils.transaction }
  )

  await utils.sequelize.query(
    `ALTER TABLE "liveVideo" ADD CONSTRAINT "live_video_valid_end_time" CHECK ("endTime" > "startTime")`,
    { transaction: utils.transaction }
  )

  await utils.sequelize.query(
    `ALTER TABLE "liveVideo" ADD CONSTRAINT "live_video_valid_status" CHECK ("status" IN ('scheduled', 'cancelled', 'completed'))`,
    { transaction: utils.transaction }
  )
}

function down (options) {
  throw new Error('Not implemented.')
}

export {
  up,
  down
}
