import { Body, Controller, Get, Inject, Post, Provide, Query } from '@midwayjs/core';
import { NetaClawDataSourceService } from '../../service/data_source.js';

@Provide()
@Controller('/admin/netaclaw/data-source')
export class NetaClawDataSourceAdminController {
  @Inject()
  dataSourceService: NetaClawDataSourceService;

  private parsePositiveInteger(value: string | number | undefined, field: string): number {
    const parsed = Number(value);
    if (!Number.isInteger(parsed) || parsed <= 0) {
      throw new Error(`${field}_invalid`);
    }
    return parsed;
  }

  @Get('/list')
  async list(@Query('agentId') agentId?: string) {
    const data = agentId !== undefined && agentId !== ''
      ? await this.dataSourceService.listForAgent(this.parsePositiveInteger(agentId, 'agent_id'))
      : await this.dataSourceService.listAdminSafe();
    return { code: 1000, data };
  }

  @Post('/save')
  async save(@Body() body: any) {
    return { code: 1000, data: await this.dataSourceService.saveConfig(body) };
  }

  @Post('/delete')
  async delete(@Body() body: { id: number | string }) {
    await this.dataSourceService.delete(this.parsePositiveInteger(body.id, 'data_source_id'));
    return { code: 1000, message: 'success' };
  }

  @Post('/test')
  async test(@Body() body: any) {
    const result = await this.dataSourceService.testConnection(body);
    if (result.ok) {
      return { code: 1000, data: result };
    }
    return {
      code: 1001,
      message: result.error || 'connection_failed',
      data: result,
    };
  }
}
