import { http } from './http';

export interface SovereigntyItem {
  id: string;
  name: string;
  status: string;
  createdAt: string;
  updatedAt?: string;
}

export interface SovereigntyDataSource {
  list(): Promise<SovereigntyItem[]>;
  create(data: Partial<SovereigntyItem>): Promise<SovereigntyItem>;
  update(id: string, data: Partial<SovereigntyItem>): Promise<SovereigntyItem>;
  delete(id: string): Promise<void>;
}

class SovereigntyApiDataSource implements SovereigntyDataSource {
  async list() {
    const response = await http.get('/api/sovereignty/list');
    return response.data.data;
  }

  async create(data: Partial<SovereigntyItem>) {
    const response = await http.post('/api/sovereignty', data);
    return response.data.data;
  }

  async update(id: string, data: Partial<SovereigntyItem>) {
    const response = await http.put(`/api/sovereignty/${id}`, data);
    return response.data.data;
  }

  async delete(id: string) {
    await http.delete(`/api/sovereignty/${id}`);
  }
}

class SovereigntyMockDataSource implements SovereigntyDataSource {
  private items: SovereigntyItem[] = [
    { id: '1', name: '示例项目 1', status: 'ACTIVE', createdAt: new Date().toISOString() },
    { id: '2', name: '示例项目 2', status: 'INACTIVE', createdAt: new Date().toISOString() },
  ];

  async list() {
    return this.items;
  }

  async create(data: Partial<SovereigntyItem>) {
    const item: SovereigntyItem = {
      id: String(this.items.length + 1),
      name: data.name || '',
      status: data.status || 'ACTIVE',
      createdAt: new Date().toISOString(),
    };
    this.items.push(item);
    return item;
  }

  async update(id: string, data: Partial<SovereigntyItem>) {
    const index = this.items.findIndex(item => item.id === id);
    if (index >= 0) {
      this.items[index] = { ...this.items[index], ...data };
      return this.items[index];
    }
    throw new Error('Item not found');
  }

  async delete(id: string) {
    const index = this.items.findIndex(item => item.id === id);
    if (index >= 0) {
      this.items.splice(index, 1);
    }
  }
}

const useMock = process.env.NODE_ENV === 'development' || process.env.REACT_APP_USE_MOCK === 'true';
export const SovereigntyDataSource: SovereigntyDataSource = useMock
  ? new SovereigntyMockDataSource()
  : new SovereigntyApiDataSource();
