import type { UserData } from '../App';
import { getPlatformConfig } from './config';

interface AuthMessage {
  access_token?: string;
  error?: string;
}

const INSTAGRAM_AUTH_URL = 'https://api.instagram.com/oauth/authorize';
const INSTAGRAM_API_URL = 'https://graph.instagram.com/me';

const instagramLogin = (): Promise<UserData> => {
  return new Promise((resolve, reject) => {
    const config = getPlatformConfig('instagram');
    if (!config.enabled || !config.key) {
      reject(new Error('Instagram is not configured or disabled'));
      return;
    }

    const clientId = config.key;
    const redirectUri = `${window.location.origin}/apps/auth/callback?shop=${window.location.origin}&platform=instagram`;
    console.log('Instagramログイン - リダイレクトURL:', redirectUri);
    const scope = 'user_profile';

    const authUrl =
      `${INSTAGRAM_AUTH_URL}?client_id=${clientId}` +
      `&redirect_uri=${encodeURIComponent(redirectUri)}` +
      `&scope=${scope}&response_type=token`;

    const width = 600;
    const height = 700;
    const left = window.screenX + (window.outerWidth - width) / 2;
    const top = window.screenY + (window.outerHeight - height) / 2;

    const authWindow = window.open(
      authUrl,
      'instagramLogin',
      `width=${width},height=${height},left=${left},top=${top}`
    );

    const handleMessage = async (event: MessageEvent<AuthMessage>) => {
      if (event.origin !== window.location.origin) return;
      const { access_token, error } = event.data || {};

      if (access_token) {
        window.removeEventListener('message', handleMessage);
        authWindow?.close();
        try {
          const userInfo = await fetch(
            `${INSTAGRAM_API_URL}?fields=id,username&access_token=${access_token}`
          ).then(res => res.json());
          const user: UserData = {
            name: userInfo.username ?? '',
            email: '',
            birthday: '',
            profileImage: '',
            platform: 'instagram'
          };
          resolve(user);
        } catch (err) {
          reject(err);
        }
      } else if (error) {
        window.removeEventListener('message', handleMessage);
        authWindow?.close();
        reject(new Error(error));
      }
    };

    window.addEventListener('message', handleMessage);
  });
};

export default instagramLogin;

