import { clearStoredAuthSession } from '@/lib/authStorage';
import { clearSupabaseAuthStorage, getSupabaseClient } from '@/lib/supabase';
import type { AuthSession, AuthUser, ChangePasswordPayload, LoginPayload, RegisterPayload } from '@/types';

const INTERNAL_EMAIL_SUFFIX = '@autoprocurement.local';

function toInternalEmail(username: string) {
  return `${username.trim().toLowerCase()}${INTERNAL_EMAIL_SUFFIX}`;
}

function clearPersistedAuthState() {
  clearStoredAuthSession();
  clearSupabaseAuthStorage();
}

function getErrorMessage(error: unknown) {
  if (error instanceof Error) {
    return error.message;
  }

  if (typeof error === 'object' && error !== null && 'message' in error) {
    return String((error as { message: unknown }).message);
  }

  return '';
}

function isStaleRefreshTokenError(error: unknown) {
  const message = getErrorMessage(error).toLowerCase();
  return message.includes('invalid refresh token')
    || message.includes('refresh token not found')
    || message.includes('refresh_token');
}

async function getRestoredSupabaseSession() {
  const supabase = getSupabaseClient();

  try {
    const { data } = await supabase.auth.getSession();
    return data.session;
  } catch (error) {
    if (isStaleRefreshTokenError(error)) {
      clearPersistedAuthState();
      return null;
    }

    throw error;
  }
}

async function fetchProfile(userId: string): Promise<{ username: string; role: 'admin' | 'user' }> {
  const supabase = getSupabaseClient();
  const { data, error } = await supabase
    .from('profiles')
    .select('username, role')
    .eq('id', userId)
    .single();
  if (error) throw new Error('获取用户信息失败');
  return data as { username: string; role: 'admin' | 'user' };
}

function toAuthUser(
  supabaseUser: { id: string; email?: string | null },
  profile: { username: string; role: 'admin' | 'user' },
): AuthUser {
  return {
    id: supabaseUser.id,
    username: profile.username,
    displayName: profile.username,
    email: supabaseUser.email ?? '',
    role: profile.role,
  };
}

/** 兼容旧调用：不再需要，保留为 no-op */
export function seedUsers() {
  /* no-op: 用户由 Supabase Auth 管理 */
}

export async function register(payload: RegisterPayload): Promise<AuthSession> {
  const supabase = getSupabaseClient();
  const email = toInternalEmail(payload.username);

  const { data, error } = await supabase.auth.signUp({
    email,
    password: payload.password,
    options: {
      data: { username: payload.username.trim() },
    },
  });

  if (error) {
    if (error.message.includes('already registered')) {
      throw new Error('该用户名已被占用');
    }
    throw new Error(error.message);
  }

  if (!data.user) throw new Error('注册失败，请重试');

  // DB 触发器会自动创建 profile；等待后 fetchProfile 读取
  const profile = await fetchProfile(data.user.id);
  const authUser = toAuthUser(data.user, profile);

  return {
    token: data.session?.access_token ?? '',
    user: authUser,
    loginAt: new Date().toISOString(),
  };
}

export async function login(payload: LoginPayload): Promise<AuthSession> {
  const supabase = getSupabaseClient();
  const email = toInternalEmail(payload.username);

  const { data, error } = await supabase.auth.signInWithPassword({
    email,
    password: payload.password,
  });

  if (error || !data.user) {
    throw new Error('用户名或密码错误');
  }

  const profile = await fetchProfile(data.user.id);
  const authUser = toAuthUser(data.user, profile);

  return {
    token: data.session.access_token,
    user: authUser,
    loginAt: new Date().toISOString(),
  };
}

export async function restoreSession(): Promise<AuthSession | null> {
  const restoredSession = await getRestoredSupabaseSession();

  if (!restoredSession) return null;

  try {
    const profile = await fetchProfile(restoredSession.user.id);
    const authUser = toAuthUser(restoredSession.user, profile);
    return {
      token: restoredSession.access_token,
      user: authUser,
      loginAt: new Date().toISOString(),
    };
  } catch {
    return null;
  }
}

export async function logout() {
  const supabase = getSupabaseClient();

  try {
    await supabase.auth.signOut();
  } finally {
    clearPersistedAuthState();
  }
}

export async function changePassword(_userId: string, payload: ChangePasswordPayload) {
  const supabase = getSupabaseClient();

  // 先用当前密码重新验证，确认原密码正确
  const { data: sessionData } = await supabase.auth.getSession();
  if (!sessionData.session) throw new Error('当前未登录');

  const { error: verifyError } = await supabase.auth.signInWithPassword({
    email: sessionData.session.user.email ?? '',
    password: payload.currentPassword,
  });
  if (verifyError) throw new Error('原密码不正确');

  const { error } = await supabase.auth.updateUser({ password: payload.newPassword });
  if (error) throw new Error('密码修改失败，请重试');
}
