import cloudClient from './cloudClient';
import CloudSyncStorage from '../services/cloudSyncStorage';
import type { Task } from '../types/task';

export interface CloudLoginRequest {
  userName: string;
  password: string;
}

export interface CloudLoginResponse {
  accessToken: string;
  expiresAtUtc: string;
  userId: string;
  role: string;
  permissions: string[];
}

export interface CloudTaskItem {
  id: number;
  title: string;
  priority: 0 | 1 | 2;
  isCompleted: boolean;
  createdAtUtc: string;
  updatedAtUtc: string;
  parentTaskId?: number | null;
}

/**
 * 把 CloudSync 的扁平任务列表（ParentTaskId）组装成前端需要的树结构（subTasks）。
 */
export const buildTaskTreeFromCloudItems = (items: CloudTaskItem[]): Task[] => {
  const map = new Map<number, Task>();
  for (const item of items) {
    map.set(item.id, {
      id: item.id,
      title: item.title ?? '',
      priority: item.priority ?? 1,
      isCompleted: Boolean(item.isCompleted),
      createdAt: item.createdAtUtc,
      updatedAt: item.updatedAtUtc,
      parentTaskId: item.parentTaskId ?? undefined,
      subTasks: [],
    });
  }

  const roots: Task[] = [];
  for (const task of map.values()) {
    const parentId = task.parentTaskId;
    if (typeof parentId === 'number' && map.has(parentId)) {
      map.get(parentId)!.subTasks.push(task);
    } else {
      roots.push(task);
    }
  }

  return roots;
};

/**
 * 云同步 API（v1.2.0 最小闭环：登录 + 拉取任务）。
 */
export const cloudSyncApi = {
  /**
   * 登录云同步服务端并保存会话（默认存入 sessionStorage）。
   */
  async login(request: CloudLoginRequest): Promise<CloudLoginResponse> {
    const response = await cloudClient.post<CloudLoginResponse>('/auth/login', request);
    const session = response.data;

    CloudSyncStorage.saveSession({
      accessToken: session.accessToken,
      expiresAtUtc: session.expiresAtUtc,
      userId: session.userId,
      role: session.role,
      permissions: Array.isArray(session.permissions) ? session.permissions : [],
    });

    return session;
  },

  /**
   * 清空云同步会话（登出）。
   */
  logout(): void {
    CloudSyncStorage.clearSession();
  },

  /**
   * 获取云端任务全量，并转换为前端树结构。
   */
  async getTasks(): Promise<Task[]> {
    const response = await cloudClient.get<CloudTaskItem[]>('/tasks/');
    const items = Array.isArray(response.data) ? response.data : [];
    return buildTaskTreeFromCloudItems(items);
  },
};

export default cloudSyncApi;
