// TaskFlow 확장 SDK 형식 정의 — SDK 판 2 (2026-10-24)
// 확장 화면(window.taskflow)과 서버 동작(action·taskflow) 둘 다. 편집기에서 자동완성·형식 검사용으로 씁니다.
//   쓰는 법: 프로젝트에 이 파일을 두고 확장 코드 맨 위에  /// <reference path="./taskflow-sdk.d.ts" />
// 사용법 문서: 개발자 문서(api-interface.html) — 확장 만들기 › 개발 안내 › 전체 개발자 문서

declare namespace TaskflowSDK {
  type TaskStatus = 'todo' | 'accepted' | 'in-progress' | 'done';
  type Priority = 'low' | 'medium' | 'high';
  type DateString = string;   // YYYY-MM-DD

  interface Task {
    id: string; title: string; status: TaskStatus; statusLabel: string; priority: Priority;
    assignees: string[]; managers: string[]; followers: string[];
    startDate: DateString | null; dueDate: DateString | null; progress: number;
    projectId: string | null; activityId: string | null; parentId: string | null; taskType: string | null;
    customFields: Record<string, unknown>; createdBy: string; createdAt: string; updatedAt: string | null;
    completedAt: string | null; archived: boolean; description?: string;
  }
  interface TaskInput {
    title?: string; description?: string; status?: TaskStatus; priority?: Priority; assignees?: string[];
    dueDate?: DateString | null; startDate?: DateString | null; progress?: number; projectId?: string | null;
    customFields?: Record<string, unknown>;
  }
  interface Project { id: string; name: string; status: string | null; color: string | null; startDate: DateString | null; endDate: DateString | null; }
  interface User { id: string; name: string; color: string | null; department: string | null; position: string | null; }
  interface DataRow<T = any> { id: string; data: T; updatedAt: string; updatedBy: string | null; }
  interface DataOptions { scope?: 'org' | 'user'; }

  // ---- 결재(SDK 판 2) ----
  type ApprovalBox = 'need' | 'soon' | 'going' | 'cc' | 'drafted' | 'archive';
  type ApprovalStatus = 'draft' | 'in_progress' | 'approved' | 'rejected' | 'canceled';
  type StepKind = 'approval' | 'agree' | 'finance_agree' | 'reference';
  interface ApprovalStep { stepOrder: number; kind: StepKind; kindLabel: string; approverId: string; state: string; stateLabel: string; opinion: string; actedAt: string | null; }
  interface ApprovalDoc {
    id: string; docNumber: string | null; title: string; docType: string | null; formId: string | null;
    status: ApprovalStatus; statusLabel: string; amount: number | null; formData: Record<string, unknown>;
    drafterId: string; drafterDept: string; currentStep: number; createdAt: string | null; submittedAt: string | null; completedAt: string | null;
    steps?: ApprovalStep[]; myTurn?: boolean;
    content?: string; attachments?: { name: string; url: string; size: number }[];
    comments?: { id: string; userId: string; content: string; createdAt: string }[];
  }
  interface ApprovalForm { id: string; title: string; docType: string; category: string; fields: { key: string; label: string; type: string; required: boolean; options: string[] }[]; }

  // ---- 매니페스트 ----
  type SlotType = 'page' | 'task-tab' | 'home-card' | 'task-action' | 'approval-section' | 'project-tab';
  type Permission = 'tasks:read' | 'tasks:write' | 'projects:read' | 'users:read' | 'approval:read' | 'approval:act';
  type ColumnType = 'text' | 'number' | 'boolean' | 'date' | 'datetime' | 'json' | 'task' | 'approval' | 'project' | 'user';
  type HookEvent = 'approval.beforeSubmit' | 'approval.beforeApprove' | 'approval.beforeReject';
  interface TableDef { label?: string; columns: Record<string, ColumnType>; }
  interface Manifest {
    slots: { type: SlotType; title: string; icon?: string; height?: number; replaces?: 'approval' }[];
    permissions: Permission[];
    network: string[];
    server?: { actions: string[]; schedules?: { action: string; every: '15m' | '30m' | '1h' | '6h' | '1d' }[] };
    tables?: Record<string, TableDef>;
    hooks?: { event: HookEvent; action: string }[];
  }

  interface Context {
    extension: { id: string; name: string; version: number; draft: boolean };
    slot: SlotType;
    user: { id: string; name: string; role: string; isManager: boolean } | null;
    task: { id: string; title: string; status: TaskStatus; priority: Priority; projectId: string | null; dueDate: DateString | null; assignees: string[] } | null;
    approval: { id: string; title: string; status: ApprovalStatus; docType: string | null; formId: string | null; docNumber: string | null; amount: number | null; drafterId: string | null; formData: Record<string, unknown> } | null;
    project: { id: string; name: string; status: string | null; startDate: DateString | null; endDate: DateString | null } | null;
    replaces: 'approval' | null;
    tables: Record<string, TableDef>;
    permissions: Permission[];
    mobile: boolean; dark: boolean; theme: Record<string, string>;
  }

  interface Client {
    version: number;
    ready(): Promise<Context>;
    readonly context: Context | null;
    onContext(fn: (ctx: Context) => void): void;
    tasks: {
      list(o?: { mine?: boolean; status?: TaskStatus | TaskStatus[]; projectId?: string; search?: string; includeDone?: boolean; ids?: string[]; limit?: number }): Promise<Task[]>;
      get(id: string): Promise<Task>;
      create(f: TaskInput & { title: string }): Promise<{ id: string }>;
      update(id: string, patch: TaskInput): Promise<Task>;
    };
    projects: { list(): Promise<Project[]> };
    users: { list(): Promise<User[]> };
    data: {
      get<T = any>(collection: string, id: string, o?: DataOptions): Promise<T | null>;
      list<T = any>(collection: string, o?: DataOptions & { limit?: number }): Promise<DataRow<T>[]>;
      query<T = any>(table: string, where: Record<string, string | number | boolean | null>, o?: DataOptions & { limit?: number; order?: 'newest' | 'oldest' }): Promise<DataRow<T>[]>;
      set(collection: string, id: string, value: unknown, o?: DataOptions): Promise<true>;
      remove(collection: string, id: string, o?: DataOptions): Promise<true>;
    };
    approval: {
      list(o?: { box?: ApprovalBox; limit?: number }): Promise<ApprovalDoc[]>;
      get(id: string): Promise<ApprovalDoc>;
      forms(): Promise<ApprovalForm[]>;
      approve(id: string, opinion?: string): Promise<{ ok: true; message: string }>;
      reject(id: string, opinion: string): Promise<{ ok: true; message: string }>;
    };
    ui: {
      toast(message: string): Promise<true>;
      openTask(id: string): Promise<boolean>;
      openApproval(id?: string | null): Promise<true>;
      navigate(tab: 'dashboard' | 'tasks' | 'projects' | 'chat' | 'communication' | 'approval' | 'attendance' | 'expense' | 'settings'): Promise<true>;
      openUrl(url: string): Promise<boolean>;
      confirm(message: string): Promise<boolean>;
      close(): Promise<true>;
    };
    server: { call<T = any>(action: string, input?: unknown): Promise<T> };
  }

  // ---- 서버 동작(우리 서버의 샌드박스) ----
  interface ServerContext { mode: 'user' | 'draft' | 'schedule'; user: { id: string; name: string } | null; extension: { id: string; version: number }; }
  interface HookInput {
    event: HookEvent;
    doc: { id: string; title: string; docType: string | null; formId: string | null; status: ApprovalStatus; docNumber: string | null; amount: number | null; formData: Record<string, unknown>; drafterId: string; drafterDept: string; contentText: string; steps: { stepOrder: number; kind: StepKind; approverId: string; state: string }[] };
    formTitle?: string; opinion?: string; step?: { kind: StepKind; stepOrder: number }; actorId?: string;
  }
  interface HookResult { block?: string; warn?: string; addSteps?: { kind: StepKind; approverId: string; position?: 'end' | 'start' | 'beforeLast' }[]; }
  interface ServerClient {
    tasks: Client['tasks']; projects: Client['projects']; users: Client['users'];
    data: {
      get<T = any>(collection: string, id: string): Promise<T | null>;
      list<T = any>(collection: string, o?: { limit?: number }): Promise<DataRow<T>[]>;
      query<T = any>(table: string, where: Record<string, string | number | boolean | null>, o?: { limit?: number }): Promise<DataRow<T>[]>;
      set(collection: string, id: string, value: unknown): Promise<true>;
      remove(collection: string, id: string): Promise<true>;
    };
    http: { fetch(url: string, o?: { method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; headers?: Record<string, string>; body?: unknown }): Promise<{ status: number; ok: boolean; contentType: string | null; text: string; json?: any }> };
    secrets: Record<string, string>;
    log(...args: unknown[]): void;
  }
}

// 확장 화면
interface Window { taskflow: TaskflowSDK.Client; }
declare const taskflow: TaskflowSDK.Client & Partial<TaskflowSDK.ServerClient>;
// 서버 동작 코드 — action(이름, 함수). 저장 전 규칙이면 input 은 HookInput, 돌려줄 값은 HookResult
declare function action<I = any, O = any>(name: string, fn: (input: I, ctx: TaskflowSDK.ServerContext) => Promise<O> | O): void;
