import { Injectable } from '@angular/core';
import Parse from 'parse';

// 添加自定义教师接口
export interface CustomTeacher {
  objectId?: string;
  userId: string;
  name: string;
  description: string;
  systemPrompt: string;
  createdAt?: Date;
  updatedAt?: Date;
}

@Injectable({
  providedIn: 'root'
})
export class DatabaseService {
  constructor() {
    // 初始化Parse
    Parse.initialize('dev'); // 使用你的 appId
    Parse.serverURL = 'http://113.44.218.121:1337/parse'; // 你的Parse服务器地址
  }

  // 创建数据
  async create(className: string, data: any) {
    try {
      const ParseObject = Parse.Object.extend(className);
      const object = new ParseObject();
      Object.keys(data).forEach(key => {
        object.set(key, data[key]);
      });
      return await object.save();
    } catch (error) {
      console.error('Error creating object:', error);
      throw error;
    }
  }

  // 查询数据
  async query(className: string, conditions?: any) {
    try {
      const query = new Parse.Query(className);
      if (conditions) {
        Object.keys(conditions).forEach(key => {
          query.equalTo(key, conditions[key]);
        });
      }
      return await query.find();
    } catch (error) {
      console.error('Error querying objects:', error);
      throw error;
    }
  }

  // 更新数据
  async update(className: string, objectId: string, data: any) {
    try {
      const query = new Parse.Query(className);
      const object = await query.get(objectId);
      Object.keys(data).forEach(key => {
        object.set(key, data[key]);
      });
      return await object.save();
    } catch (error) {
      console.error('Error updating object:', error);
      throw error;
    }
  }

  // 删除数据
  async delete(className: string, objectId: string) {
    try {
      const query = new Parse.Query(className);
      const object = await query.get(objectId);
      return await object.destroy();
    } catch (error) {
      console.error('Error deleting object:', error);
      throw error;
    }
  }

  // 添加测试方法
  async testConnection() {
    try {
      const TestObject = Parse.Object.extend('TestObject');
      const testObject = new TestObject();
      testObject.set('foo', 'bar');
      await testObject.save();
      console.log('Successfully connected to database!');
      return true;
    } catch (error) {
      console.error('Database connection test failed:', error);
      return false;
    }
  }

  // 获取用户的自定义教师列表
  async getUserCustomTeachers(userId: string): Promise<CustomTeacher[]> {
    try {
      const query = new Parse.Query('CustomTeacher');
      query.equalTo('userId', userId);
      query.ascending('createdAt');
      const results = await query.find();
      return results.map(obj => ({
        objectId: obj.id,
        userId: obj.get('userId'),
        name: obj.get('name'),
        description: obj.get('description'),
        systemPrompt: obj.get('systemPrompt'),
        createdAt: obj.get('createdAt'),
        updatedAt: obj.get('updatedAt')
      }));
    } catch (error) {
      console.error('Error getting custom teachers:', error);
      throw error;
    }
  }

  // 创建自定义教师
  async createCustomTeacher(teacherData: CustomTeacher): Promise<CustomTeacher> {
    try {
      const CustomTeacher = Parse.Object.extend('CustomTeacher');
      const teacher = new CustomTeacher();
      
      // 使用类型断言确保字段名是字符串
      const fields = ['userId', 'name', 'description', 'systemPrompt'] as const;
      fields.forEach(field => {
        if (field in teacherData) {
          teacher.set(field as string, teacherData[field]);
        }
      });
      
      const result = await teacher.save();
      return {
        objectId: result.id,
        userId: result.get('userId'),
        name: result.get('name'),
        description: result.get('description'),
        systemPrompt: result.get('systemPrompt'),
        createdAt: result.get('createdAt'),
        updatedAt: result.get('updatedAt')
      };
    } catch (error) {
      console.error('Error creating custom teacher:', error);
      throw error;
    }
  }

  // 更新自定义教师
  async updateCustomTeacher(objectId: string, teacherData: Partial<CustomTeacher>): Promise<CustomTeacher> {
    try {
      const query = new Parse.Query('CustomTeacher');
      const teacher = await query.get(objectId);
      
      // 使用类型断言确保字段名是字符串
      const updateableFields = ['name', 'description', 'systemPrompt'] as const;
      updateableFields.forEach(field => {
        if (field in teacherData) {
          teacher.set(field as string, teacherData[field]);
        }
      });
      
      const result = await teacher.save();
      return {
        objectId: result.id,
        userId: result.get('userId'),
        name: result.get('name'),
        description: result.get('description'),
        systemPrompt: result.get('systemPrompt'),
        createdAt: result.get('createdAt'),
        updatedAt: result.get('updatedAt')
      };
    } catch (error) {
      console.error('Error updating custom teacher:', error);
      throw error;
    }
  }

  // 删除自定义教师
  async deleteCustomTeacher(objectId: string): Promise<void> {
    try {
      const query = new Parse.Query('CustomTeacher');
      const teacher = await query.get(objectId);
      await teacher.destroy();
    } catch (error) {
      console.error('Error deleting custom teacher:', error);
      throw error;
    }
  }
} 