import { exportJWK, generateKeyPair } from 'jose';
import { Provider } from 'oidc-provider';

const ISSUER = process.env.MOCK_OIDC_ISSUER ?? 'http://localhost:5556';
const PROVIDER_ID =
  process.env.MAS_PROVIDER_ID ?? '01JQ0FAKEG00G1E0D1CPR0V1D3';
const CLIENT_ID = process.env.MOCK_OIDC_CLIENT_ID ?? 'mas-dev';
const CLIENT_SECRET =
  process.env.MOCK_OIDC_CLIENT_SECRET ?? 'mas-dev-secret';

const redirectUris = [
  `http://localhost:8080/upstream/callback/${PROVIDER_ID}`,
  `http://127.0.0.1:8080/upstream/callback/${PROVIDER_ID}`,
  `http://[::]:8080/upstream/callback/${PROVIDER_ID}`,
];

const { privateKey } = await generateKeyPair('RS256', { extractable: true });
const jwk = await exportJWK(privateKey);
jwk.use = 'sig';
jwk.alg = 'RS256';
jwk.kid = 'mock-google-rs256';

const configuration = {
  clients: [
    {
      client_id: CLIENT_ID,
      client_secret: CLIENT_SECRET,
      redirect_uris: redirectUris,
      response_types: ['code'],
      grant_types: ['authorization_code'],
      token_endpoint_auth_method: 'client_secret_post',
    },
  ],
  jwks: { keys: [jwk] },
  claims: {
    openid: ['sub'],
    email: ['email', 'email_verified'],
    profile: ['name', 'preferred_username', 'picture'],
  },
  cookies: {
    keys: ['mock-google-oidc-dev-key-1', 'mock-google-oidc-dev-key-2'],
  },
  features: {
    devInteractions: { enabled: true },
    rpInitiatedLogout: { enabled: false },
  },
  async findAccount(_ctx, sub) {
    const email = sub.includes('@') ? sub : `${sub}@gmail.com`;
    const preferredUsername = email.split('@')[0];

    return {
      accountId: sub,
      async claims(_use, _scope) {
        return {
          sub,
          email,
          email_verified: true,
          name: 'Taylor Google User',
          preferred_username: preferredUsername,
          picture:
            'https://www.gstatic.com/images/branding/product/1x/avatar_circle_blue_512dp.png',
        };
      },
    };
  },
};

const provider = new Provider(ISSUER, configuration);

provider.listen(5556, () => {
  console.log(`Mock Google OIDC running at ${ISSUER}`);
  console.log('Configured redirect URIs:');
  for (const uri of redirectUris) {
    console.log(`  - ${uri}`);
  }
  console.log('Use any email-like value in the dev interaction login form.');
});
