import { ConflictException, Injectable } from '@nestjs/common';
import type { AppDataKey } from '../data/data-keys';

export type AppDataRetirementState = 'active' | 'write_frozen' | 'read_only_archive';

export interface AppDataRetirementEntry {
  state: AppDataRetirementState;
  replacement: string;
  note?: string;
}

export const APP_DATA_RETIREMENT_CONFIG = {
  'products-overview': {
    state: 'write_frozen',
    replacement: '/api/v1/products, /api/v1/products/:productId/projects, /api/v1/products/:productId/versions',
  },
  requirements: {
    state: 'write_frozen',
    replacement: '/api/v1/products/:productId/requirements',
  },
  'version-plans': {
    state: 'write_frozen',
    replacement: '/api/v1/versions/:versionId/plans',
  },
  'dev-tasks': {
    state: 'write_frozen',
    replacement: '/api/v1/versions/:versionId/dev-tasks',
  },
  'test-cases': {
    state: 'write_frozen',
    replacement: '/api/v1/versions/:versionId/test-cases',
  },
  bugs: {
    state: 'write_frozen',
    replacement: '/api/v1/versions/:versionId/bugs',
  },
  members: {
    state: 'write_frozen',
    replacement: '/api/v1/members',
    note: '成员身份已迁移；部门、角色和密码策略仍需 V2.7 配置表承接。',
  },
  'task-categories': {
    state: 'write_frozen',
    replacement: '/api/v1/task-categories',
  },
  'task-worklogs': {
    state: 'write_frozen',
    replacement: '/api/v1/task-worklogs',
  },
  'work-activities': {
    state: 'write_frozen',
    replacement: '/api/v1/work-activities',
  },
  'xiaobao-risk-insights': {
    state: 'read_only_archive',
    replacement: 'V2.6 Xiaobao relation writer backed by xiaobao_risk_insights',
    note: '风险解读缓存不再扩大 AppData 主写路径，后台化由 V2.6 承接。',
  },
  'xiaobao-risk-snapshots': {
    state: 'read_only_archive',
    replacement: 'V2.6 Xiaobao relation writer backed by xiaobao_risk_snapshots',
    note: '风险快照不再扩大 AppData 主写路径，后台化由 V2.6 承接。',
  },
  'xiaobao-warning-views': {
    state: 'read_only_archive',
    replacement: 'V2.7 per-user warning read-state API',
    note: '个人已读状态等待企业协作/通知治理阶段承接。',
  },
  overtime: {
    state: 'write_frozen',
    replacement: '/api/v1/overtime',
    note: '加班记录已迁移；加班原因配置仍需 V2.7 配置表承接。',
  },
} satisfies Record<AppDataKey, AppDataRetirementEntry>;

@Injectable()
export class AppDataRetirementService {
  getEntry(key: AppDataKey): AppDataRetirementEntry {
    return APP_DATA_RETIREMENT_CONFIG[key];
  }

  assertWritable(key: AppDataKey) {
    const entry = this.getEntry(key);
    if (entry.state === 'active') return;

    throw new ConflictException({
      code: 'APP_DATA_WRITE_FROZEN',
      message: `AppData key "${key}" is ${entry.state}; use ${entry.replacement} instead.`,
      key,
      state: entry.state,
      replacement: entry.replacement,
      note: entry.note,
    });
  }
}
