import { Body, Controller, ForbiddenException, Get, Param, Post, Put, Req, Res, Sse, Headers } from '@nestjs/common'
import { Org } from './entities/org.entity'
import { PageRequest } from '../common/dto/page-request'
import { OrgService } from './org.service'
import { HasRoles } from '../auth/roles.decorator'
import { Role } from '../model/role.enum'
import { Public } from 'src/auth/public.decorator'

@Controller('org')
export class OrgController {
    constructor(private readonly orgService: OrgService) {}

    @Get()
    @Public()
    async getOrgFromUrl(@Headers('host') host) {
        return await this.orgService.findByUrl(host.replace(/^http(s?):\/\//, '').replace(/\/$/, ''))
    }

    @Get('/my')
    async my(@Req() req) {
        if (!req.user.orgId) {
            throw new ForbiddenException('You are not a member of any organization')
        }
        return await this.orgService.findById(req.user.orgId)
    }

    @Get('/:id')
    @Public()
    async get(@Param('id') id: string) {
        return await this.orgService.findById(Number(id))
    }

    @Put('/my')
    async update(@Req() req, @Body() org: Org) {
        if (!req.user.orgId) {
            throw new ForbiddenException('You are not a member of any organization')
        }
        org.id = req.user.orgId
        return await this.orgService.update(org)
    }

    @Post('/:id/ask')
    async ask(
        @Req() req,
        @Param('id') id: string,
        @Body()
        body: {
            prompt: string
            options: {
                parentMessageId?: string
            }
            knowledgeId?: number
            fileId?: number
        }
    ) {
        const orgId = Number(id)
        // if (req.user.orgId != orgId) {
        //     throw new ForbiddenException('You are not a member of this organization')
        // }
        return await this.orgService.ask(body.prompt, orgId, body.options?.parentMessageId, body.knowledgeId, body.fileId)
    }

    @Post('/:id/streamAsk')
    @Sse()
    async streamAsk(@Req() req, @Res() res, @Param('id') id: string, @Body() body: { prompt: string }) {
        const orgId = Number(id)
        // if (req.user.orgId != orgId) {
        //     throw new ForbiddenException('You are not a member of this organization')
        // }
        await this.orgService.streamAsk(req, res, body.prompt, orgId)
    }
}
