import request from './request';
import type {
  PlatformAccount,
  AccountGroup,
  AddPlatformAccountRequest,
  UpdatePlatformAccountRequest,
  CreateAccountGroupRequest,
  QRCodeInfo,
  LoginStatusResult,
} from '@media-manager/shared';

export const accountsApi = {
  // 账号分组
  getGroups(): Promise<AccountGroup[]> {
    return request.get('/api/accounts/groups');
  },

  createGroup(data: CreateAccountGroupRequest): Promise<AccountGroup> {
    return request.post('/api/accounts/groups', data);
  },

  updateGroup(id: number, data: Partial<CreateAccountGroupRequest>): Promise<AccountGroup> {
    return request.put(`/api/accounts/groups/${id}`, data);
  },

  deleteGroup(id: number): Promise<void> {
    return request.delete(`/api/accounts/groups/${id}`);
  },

  // 平台账号
  getAccounts(params?: { platform?: string; groupId?: number; status?: string }): Promise<PlatformAccount[]> {
    return request.get('/api/accounts', { params });
  },

  getAccount(id: number): Promise<PlatformAccount> {
    return request.get(`/api/accounts/${id}`);
  },

  addAccount(data: AddPlatformAccountRequest & {
    accountInfo?: {
      accountId?: string;
      accountName?: string;
      avatarUrl?: string;
      fansCount?: number;
      worksCount?: number;
    };
  }): Promise<PlatformAccount> {
    return request.post('/api/accounts', data);
  },

  updateAccount(id: number, data: UpdatePlatformAccountRequest): Promise<PlatformAccount> {
    return request.put(`/api/accounts/${id}`, data);
  },

  deleteAccount(id: number): Promise<void> {
    return request.delete(`/api/accounts/${id}`);
  },

  refreshAccount(id: number): Promise<{ account: PlatformAccount; needReLogin: boolean }> {
    return request.post(`/api/accounts/${id}/refresh`, {}, { timeout: 120000 }).then((data: PlatformAccount & { needReLogin?: boolean }) => {
      const { needReLogin, ...account } = data as PlatformAccount & { needReLogin?: boolean };
      return { account: account as PlatformAccount, needReLogin: needReLogin || false };
    });
  },

  // 批量刷新所有账号状态
  refreshAllAccounts(): Promise<{ refreshed: number; failed: number }> {
    return request.post('/api/accounts/refresh-all', {}, { timeout: 300000 }); // 5分钟超时
  },

  // 检查账号 Cookie 是否有效
  checkAccountStatus(id: number): Promise<{ isValid: boolean; needReLogin: boolean }> {
    return request.get(`/api/accounts/${id}/check-status`, { timeout: 120000 }); // 2分钟超时
  },

  // 扫码登录
  getQRCode(platform: string): Promise<QRCodeInfo> {
    return request.post('/api/accounts/qrcode', { platform });
  },

  checkQRCodeStatus(platform: string, qrcodeKey: string): Promise<LoginStatusResult> {
    return request.get('/api/accounts/qrcode/status', { params: { platform, qrcodeKey } });
  },

  // 浏览器登录
  startBrowserLogin(platform: string): Promise<{ sessionId: string; message: string }> {
    return request.post('/api/accounts/browser-login', { platform });
  },

  getBrowserLoginStatus(sessionId: string): Promise<{
    status: string;
    cookies?: string;
    error?: string;
    accountInfo?: {
      accountId: string;
      accountName: string;
      avatarUrl: string;
      fansCount: number;
      worksCount: number;
    };
  }> {
    return request.get(`/api/accounts/browser-login/${sessionId}`);
  },

  cancelBrowserLogin(sessionId: string): Promise<void> {
    return request.delete(`/api/accounts/browser-login/${sessionId}`);
  },

  confirmBrowserLogin(sessionId: string, platform: string, groupId?: number): Promise<PlatformAccount> {
    return request.post(`/api/accounts/browser-login/${sessionId}/confirm`, { platform, groupId });
  },

  // 验证 Cookie 登录状态（用于内嵌浏览器登录）
  verifyLoginCookie(platform: string, cookieData: string): Promise<{
    success: boolean;
    message?: string;
    accountInfo?: {
      accountId: string;
      accountName: string;
      avatarUrl: string;
      fansCount: number;
      worksCount: number;
    };
  }> {
    return request.post('/api/accounts/verify-cookie', { platform, cookieData }, { timeout: 120000 }); // 2分钟超时
  },

  // 获取账号 Cookie（用于打开后台）
  getAccountCookie(id: number): Promise<{ cookieData: string }> {
    return request.get(`/api/accounts/${id}/cookie`);
  },
};
