import Store from 'electron-store';
import { Subject } from 'rxjs';
import log from 'electron-log';

export interface ActionEntry {
  id: string;
  url: string;
  timestamp: number;
  logs: string[];
  status: 'pending' | 'running' | 'completed' | 'failed';
}

export interface ActionsData {
  actions: ActionEntry[];
}

const defaultActionsData: ActionsData = {
  actions: []
};

class ActionsStore {
  private store: Store<ActionsData>;
  public actionsChanged$ = new Subject<ActionEntry>();

  constructor() {
    this.store = new Store<ActionsData>({
      defaults: defaultActionsData,
      name: 'actions'
    });

    log.info('Actions store initialized');
  }

  getAll(): ActionEntry[] {
    return this.store.get('actions', []);
  }

  add(url: string): ActionEntry {
    const action: ActionEntry = {
      id: `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      url,
      timestamp: Date.now(),
      logs: [],
      status: 'pending'
    };

    const actions = this.getAll();
    actions.unshift(action); // Add to beginning
    this.store.set('actions', actions);
    this.actionsChanged$.next(action);

    log.info(`Action added: ${action.id} - ${url}`);
    return action;
  }

  get(id: string): ActionEntry | undefined {
    const actions = this.getAll();
    return actions.find(a => a.id === id);
  }

  update(id: string, updates: Partial<ActionEntry>): void {
    const actions = this.getAll();
    const index = actions.findIndex(a => a.id === id);

    if (index !== -1) {
      actions[index] = { ...actions[index], ...updates };
      this.store.set('actions', actions);
      this.actionsChanged$.next(actions[index]);
      log.info(`Action updated: ${id}`);
    }
  }

  addLog(id: string, logLine: string): void {
    const actions = this.getAll();
    const action = actions.find(a => a.id === id);

    if (action) {
      action.logs.push(logLine);
      this.store.set('actions', actions);
      log.info(`Log added to action ${id}: ${logLine}`);
    }
  }

  delete(id: string): void {
    const actions = this.getAll();
    const filtered = actions.filter(a => a.id !== id);
    this.store.set('actions', filtered);
    log.info(`Action deleted: ${id}`);
  }

  clear(): void {
    this.store.set('actions', []);
    log.info('All actions cleared');
  }
}

export const actionsStore = new ActionsStore();
