import 'package:drift/drift.dart';
import 'package:im_app/data/local/drift/app_database.dart';
import 'package:im_app/domain/entities/workspace.dart';
import 'package:im_app/domain/repositories/workspace_repository.dart';
import 'package:storage_sdk/storage_sdk.dart';

class WorkspaceRepositoryImpl implements WorkspaceRepository {
  final StorageSdkApi _storage;

  WorkspaceRepositoryImpl(this._storage);

  // ── DB row → Domain ──────────────────────────────────────────────────────

  Workspace _toEntity(DriftWorkspace row) => Workspace(
    id: row.id,
    name: row.name,
    ownerId: row.ownerId,
    description: row.description,
    logo: row.logo,
    grade: row.grade,
    cap: row.cap,
    currency: row.currency,
    status: row.status,
    createdAt: row.createdAt,
    updatedAt: row.updatedAt,
    deletedAt: row.deletedAt,
    channelGroupId: row.channelGroupId,
  );

  // ── Domain → DB companion (internal only) ────────────────────────────────

  WorkspacesCompanion _toCompanion(Workspace workspace) => WorkspacesCompanion(
    id: Value(workspace.id),
    name: Value(workspace.name),
    ownerId: Value(workspace.ownerId),
    description: Value(workspace.description),
    logo: Value(workspace.logo),
    grade: Value(workspace.grade),
    cap: Value(workspace.cap),
    currency: Value(workspace.currency),
    status: Value(workspace.status),
    createdAt: Value(workspace.createdAt),
    updatedAt: Value(workspace.updatedAt),
    deletedAt: Value(workspace.deletedAt),
    channelGroupId: Value(workspace.channelGroupId),
  );

  // ── 监听 ─────────────────────────────────────────────────────────────────

  @override
  Stream<List<Workspace>> watchAll() {
    return _storage.watchAll<DriftWorkspace>().map(
      (rows) => rows.map(_toEntity).toList(),
    );
  }

  @override
  Stream<Workspace?> watchById(int id) {
    return _storage
        .watchFirst<DriftWorkspace, $WorkspacesTable>((t) => t.id.equals(id))
        .map((row) => row != null ? _toEntity(row) : null);
  }

  // ── 读取 ─────────────────────────────────────────────────────────────────

  @override
  Future<List<Workspace>> getAll() async {
    final rows = await _storage.selectAll<DriftWorkspace>();
    return rows.map(_toEntity).toList();
  }

  @override
  Future<Workspace?> getById(int id) async {
    final row = await _storage.selectFirst<DriftWorkspace, $WorkspacesTable>(
      (t) => t.id.equals(id),
    );
    return row != null ? _toEntity(row) : null;
  }

  @override
  Future<List<Workspace>> getByOwner(int ownerId) async {
    final rows = await _storage.selectWhere<DriftWorkspace, $WorkspacesTable>(
      (t) => t.ownerId.equals(ownerId),
    );
    return rows.map(_toEntity).toList();
  }

  // ── 写入 ─────────────────────────────────────────────────────────────────

  @override
  Future<void> insertOrReplace(Workspace workspace) async {
    await _storage.insertOrReplace<DriftWorkspace>(_toCompanion(workspace));
  }

  @override
  Future<void> insertOrReplaceAll(List<Workspace> workspaces) async {
    await _storage.batchInsertOrReplace<DriftWorkspace>(
      workspaces.map(_toCompanion).toList(),
    );
  }

  @override
  Future<void> update(Workspace workspace) async {
    await _storage.updateWhere<DriftWorkspace, $WorkspacesTable>(
      _toCompanion(workspace),
      (t) => t.id.equals(workspace.id),
    );
  }

  // ── 删除 ─────────────────────────────────────────────────────────────────

  @override
  Future<void> delete(int id) async {
    await _storage.deleteWhere<DriftWorkspace, $WorkspacesTable>(
      (t) => t.id.equals(id),
    );
  }

  @override
  Future<void> clear() async {
    await _storage.deleteAll<DriftWorkspace>();
  }
}
