import type * as mediasoup from 'mediasoup'
import fp from 'fastify-plugin'

declare module 'fastify' {
  interface FastifyInstance {
    mediasoupRouter: mediasoup.types.Router
  }
}

export default fp<mediasoup.types.RouterOptions>(
  async (fastify, opts) => {
    const router = await fastify.mediasoupWorker.createRouter(opts)

    fastify.decorate('mediasoupRouter', router)
  },
  { name: 'mediasoup-router', dependencies: ['mediasoup-worker'] },
)

export const autoConfig: mediasoup.types.RouterOptions = {
  mediaCodecs: [
    {
      kind: 'audio',
      mimeType: 'audio/opus',
      clockRate: 48000,
      channels: 2,
      parameters: { useinbandfec: 0, stereo: 1 },
    },
    {
      kind: 'video',
      mimeType: 'video/AV1',
      clockRate: 90000,
      parameters: {
        'level-idx': 13, // Level 4.1 — 1080p60
        'profile': 0, // Main Profile
        'tier': 0, // Main tier (0) vs High tier (1)
        'x-google-start-bitrate': 8000,
      },
    },
    {
      kind: 'video',
      mimeType: 'video/AV1',
      clockRate: 90000,
      parameters: {},
    },
    // {
    //   kind: 'video',
    //   mimeType: 'video/h264',
    //   clockRate: 90000,
    //   parameters: {
    //     'packetization-mode': 1,
    //     'profile-level-id': '640032',
    //     'level-asymmetry-allowed': 1,
    //     'x-google-start-bitrate': 12000,
    //   },
    // },
    {
      kind: 'video',
      mimeType: 'video/h264',
      clockRate: 90000,
      parameters: {
        'packetization-mode': 1,
        'profile-level-id': '4d0032',
        'level-asymmetry-allowed': 1,
        'x-google-start-bitrate': 8000,
      },
    },
    {
      kind: 'video',
      mimeType: 'video/h264',
      clockRate: 90000,
      parameters: {
        'packetization-mode': 1,
        'profile-level-id': '42e01f',
        'level-asymmetry-allowed': 1,
        'x-google-start-bitrate': 8000,
      },
    },
    {
      kind: 'video',
      mimeType: 'video/VP9',
      clockRate: 90000,
      parameters: {
        'profile-id': 0,
        'x-google-start-bitrate': 12000,
      },
    },
    {
      kind: 'video',
      mimeType: 'video/VP8',
      clockRate: 90000,
      parameters: {
        'x-google-start-bitrate': 2000,
      },
    },
  ],
}
