import type { Project, StudentRecord } from '../Domain/Project';

const STORAGE_KEYS = {
  PROJECTS: 'swimming_projects',
  RECORDS: 'swimming_records',
};

export class StorageManager {
  static async getProjects(): Promise<Project[]> {
    try {
      const data = uni.getStorageSync(STORAGE_KEYS.PROJECTS);
      return data ? JSON.parse(data) : [];
    } catch {
      return [];
    }
  }

  static async saveProjects(projects: Project[]): Promise<void> {
    uni.setStorageSync(STORAGE_KEYS.PROJECTS, JSON.stringify(projects));
  }

  static async addProject(project: Project): Promise<void> {
    const projects = await this.getProjects();
    projects.unshift(project);
    await this.saveProjects(projects);
  }

  static async deleteProject(projectId: string): Promise<void> {
    const projects = await this.getProjects();
    const filtered = projects.filter(p => p.id !== projectId);
    await this.saveProjects(filtered);
  }

  static async getRecordsByProject(projectId: string): Promise<StudentRecord[]> {
    try {
      const data = uni.getStorageSync(STORAGE_KEYS.RECORDS);
      const records: StudentRecord[] = data ? JSON.parse(data) : [];
      return records.filter(r => r.projectId === projectId);
    } catch {
      return [];
    }
  }

  static async saveRecords(records: StudentRecord[]): Promise<void> {
    uni.setStorageSync(STORAGE_KEYS.RECORDS, JSON.stringify(records));
  }

  static async addRecord(record: StudentRecord): Promise<void> {
    try {
      const data = uni.getStorageSync(STORAGE_KEYS.RECORDS);
      const records: StudentRecord[] = data ? JSON.parse(data) : [];
      records.unshift(record);
      await this.saveRecords(records);
    } catch {
      const records: StudentRecord[] = [record];
      await this.saveRecords(records);
    }
  }

  static async deleteRecord(recordId: string): Promise<void> {
    try {
      const data = uni.getStorageSync(STORAGE_KEYS.RECORDS);
      const records: StudentRecord[] = data ? JSON.parse(data) : [];
      const filtered = records.filter(r => r.id !== recordId);
      await this.saveRecords(filtered);
    } catch {
    }
  }
}
