import { TestStore } from './sqlite.ts'
import { execFileSync } from 'node:child_process'
import { registerHooks } from 'node:module'
const g: any = globalThis
export const fixture = g.authFixture = {
store: new TestStore(), mapped: true, updatedAt: '1', description: JSON.stringify({registration:'00000000-0000-4000-8000-000000000001'}), disconnected: false,
opens: 0, fetches: 0,
context: {} as Record<string, unknown>,
beforeSql: async (_query: string, _params: unknown[]) => {},
afterGet: async (_key: string, _value: unknown) => {},
beforeSet: async (_key: string, _value: unknown) => {},
beforeOpen: async () => {},
afterMetadata: async () => {},
provider: async (_url: string, _init?: RequestInit): Promise<Response> => Response.json({}),
}
export function reset() {
fixture.store.clear();fixture.mapped=true;fixture.updatedAt='1';fixture.description=JSON.stringify({registration:'00000000-0000-4000-8000-000000000001'});fixture.disconnected=false
fixture.opens=0;fixture.fetches=0
fixture.beforeSql=async()=>{};fixture.afterGet=async()=>{};fixture.beforeSet=async()=>{};fixture.beforeOpen=async()=>{};fixture.afterMetadata=async()=>{}
fixture.provider=async()=>Response.json({})
}
registerHooks({
resolve(s,c,n){
if(s==='kody:runtime')return {url:'mock:auth-runtime',shortCircuit:true}
if(process.env.AUTH_TEST_BASE&&s.startsWith('./')&&c.parentURL?.startsWith(new URL('../../',import.meta.url).href)) return {url:new URL(s,c.parentURL).href,shortCircuit:true}
return n(s,c)
},
load(u,c,n){
if(process.env.AUTH_TEST_BASE&&u.startsWith(new URL('../../',import.meta.url).href)&&!u.includes('/__tests__/')) return {format:'module-typescript',shortCircuit:true,source:execFileSync('git',['show',`${process.env.AUTH_TEST_BASE}:src/${u.split('/').at(-1)}`],{encoding:'utf8'})}
return u==='mock:auth-runtime'?{format:'module',shortCircuit:true,source:`
const f=globalThis.authFixture;
export const packageStorage=()=>({get:async k=>{const v=structuredClone(f.store.get(k));await f.afterGet(k,v);return v},set:async(k,v)=>{await f.beforeSet(k,v);return f.store.set(k,structuredClone(v))},delete:async k=>f.store.delete(k),sql:async(q,p=[])=>{await f.beforeSql(q,p);return f.store.sql(q,p)}});
export const kody={secretList:async()=>{const row={name:'audible-login',scope:'user',updated_at:f.updatedAt,description:f.description,disconnected:f.disconnected};await f.afterMetadata();return{secrets:[row]}}};
export const credential=async()=>{f.opens++;await f.beforeOpen();if(!f.mapped)throw new Error('credential_unbound');return{name:'audible-login',scope:'org',kind:'login',hosts:['api.audible.ca','api.amazon.ca'],fetch:async(...a)=>{f.fetches++;return f.provider(...a)}}};
export const packageContext=f.context;`}:n(u,c)},
})