import { BskyAgent } from '@atproto/api';
import { OAuth2Authenticator, Client } from 'mixi2-js';

// GitHubから直接入力されたテキストを受け取る
const messageText = process.env.POST_TEXT;

if (!messageText) {
  console.error("投稿するテキストがありません。");
  process.exit(1);
}

// 🦋 Blueskyへの投稿処理
async function postToBluesky(text) {
  console.log("Blueskyへの投稿を開始します...");
  try {
    const agent = new BskyAgent({ service: '<https://bsky.social>' });
    await agent.login({
      identifier: process.env.BLUESKY_HANDLE,
      password: process.env.BLUESKY_APP_PASSWORD,
    });
    
    await agent.post({
      text: text,
      createdAt: new Date().toISOString(),
    });
    console.log("✅ Blueskyへの投稿に成功しました。");
  } catch (error) {
    console.error("❌ Blueskyへの投稿に失敗しました:", error.message);
  }
}

// 🟠 mixi2への投稿処理
async function postToMixi2(text) {
  console.log("mixi2への投稿を開始します...");
  try {
    const authenticator = new OAuth2Authenticator({
      clientId: process.env.MIXI2_CLIENT_ID,
      clientSecret: process.env.MIXI2_CLIENT_SECRET,
      tokenUrl: '<https://application-auth.mixi.social/oauth2/token>'
    });

    const client = new Client({
      apiAddress: 'application-api.mixi.social:443',
      authenticator: authenticator
    });

    await client.createPost({
      text: text
    });
    console.log("✅ mixi2への投稿に成功しました。");
  } catch (error) {
    console.error("❌ mixi2への投稿に失敗しました:", error.message);
  }
}

// 🥝 Misskey.ioへの投稿処理
async function postToMisskey(text) {
  console.log("Misskey.ioへの投稿を開始します...");
  try {
    const response = await fetch('<https://misskey.io/api/notes/create>', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        i: process.env.MISSKEY_TOKEN,
        text: text
      })
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(JSON.stringify(errorData));
    }
    console.log("✅ Misskey.ioへの投稿に成功しました。");
  } catch (error) {
    console.error("❌ Misskey.ioへの投稿に失敗しました:", error.message);
  }
}

// ⚔️ 3つのSNSへ同時に投稿を実行
async function main() {
  await Promise.all([
    postToBluesky(messageText),
    postToMixi2(messageText),
    postToMisskey(messageText) 
  ]);
}

main();