import type {
  CaptchaEngine,
  CaptchaProvider,
  CreateCaptchaOptions,
  VerifyCaptchaInput,
} from "../types.ts";

export class SelfHostedCaptchaProvider implements CaptchaProvider {
  readonly name = "self-hosted" as const;
  readonly client;

  constructor(readonly engine: CaptchaEngine) {
    this.client = {
      responseField: "wrn-captcha-response",
      managedCreateUrl: `${engine.basePath}/challenge`,
    };
  }

  createChallenge(options: CreateCaptchaOptions) {
    return this.engine.create(options);
  }

  verify(input: VerifyCaptchaInput) {
    return input.responseToken || input.providerToken
      ? this.engine.verifyResponseToken({
          ...input,
          responseToken: input.responseToken ?? input.providerToken,
        })
      : this.engine.verify(input);
  }
}

export function selfHostedProvider(engine: CaptchaEngine): SelfHostedCaptchaProvider {
  return new SelfHostedCaptchaProvider(engine);
}
