import { Body, Controller, Get, Injectable, Post } from '@nestjs/common';

import { ApiTags } from '@nestjs/swagger';
import { Public } from 'src/core/guards';
import * as Nano from 'nano';
import { CreateUserPrivilegeDto } from 'src/modules/user-related/user-privilege/infrastructure/dto/create-user-privilege.dto';
import { ConfigService } from '@nestjs/config';
import { CouchService } from '../data/services/couch.service';

@ApiTags(`couch`)
@Controller('v1/couch')
@Public()
@Injectable()
export class CouchDataController {
  constructor(
    private configService: ConfigService,
    private couchService: CouchService,
  ) {}

  get nanoInstance() {
    const couchConfiguration = this.configService.get<string>('COUCHDB_CONFIG');
    return Nano(couchConfiguration);
  }

  @Post()
  async createDoc(@Body() entity: CreateUserPrivilegeDto) {
    try {
      const n = this.nanoInstance;
      await n.db.create(entity.name);
    } catch (error) {}
  }

  @Post('doc')
  async createDocs(@Body() entity: CreateUserPrivilegeDto) {
    try {
      const nano = this.nanoInstance;
      const people = nano.db.use('string');
      // const data = {
      //   id: '1212',
      //   name: 'dsadas',
      // };
      // await people.insert(data)

      people.changesReader
        .start({})
        .on('change', (change) => {
          console.log(change);
        })
        .on('batch', (b) => {
          console.log('a batch of', b.length, 'changes has arrived');
        })
        .on('seq', (s) => {
          console.log('sequence token', s);
        })
        .on('error', (e) => {
          console.error('error', e);
        });
    } catch (error) {}
  }

  @Get()
  async getDoc() {
    try {
      const n = this.nanoInstance;
      const people = n.db.get('user');

      return people;
      // return people.get();
    } catch (error) {}
  }

  @Public(true)
  @Get('clear-transactions')
  async clearTransactions(): Promise<string> {
    await this.couchService.clearTransactions();
    return 'OK';
  }
}
