import { describe, test, expect, vi } from 'vitest'
import { handleFrpHook, type ControlPlaneAuthz } from '../frp-scaffold/plugin-hook.js'

function authz(allow: boolean): ControlPlaneAuthz {
  return { authorize: vi.fn(async () => ({ allow })) }
}

const loginReq = { version: '0.1.0', op: 'Login', content: { user: 'alice', token: 't' } }

describe('frp plugin-hook shim (T12, deny-by-default, delegates to P3)', () => {
  test('unknown token → reject (deny-by-default)', async () => {
    const res = await handleFrpHook({ ...loginReq, op: 'NewUserConn' }, authz(false))
    expect(res).toEqual({ reject: true, reject_reason: 'denied by control plane' })
  })

  test('valid + control-plane-owned subdomain → allow (pass-through unchanged)', async () => {
    const res = await handleFrpHook(loginReq, authz(true))
    expect(res).toEqual({ reject: false, unchange: true })
  })

  test('forwards the decision to P3, never decides tenancy itself', async () => {
    const a = authz(true)
    await handleFrpHook({ ...loginReq, op: 'NewProxy' }, a)
    expect(a.authorize).toHaveBeenCalledWith('NewProxy', loginReq.content)
  })

  test('malformed payload → reject at the Zod boundary, authorizer NOT called', async () => {
    const a = authz(true)
    const res = await handleFrpHook({ op: 'Bogus' }, a)
    expect(res).toEqual({ reject: true, reject_reason: 'malformed hook request' })
    expect(a.authorize).not.toHaveBeenCalled()
  })
})
