
import { Request, Response } from 'express';
import * as yieldStudyService from '../services/yieldStudyService.js';

export const getAllStudies = async (req: Request, res: Response) => {
    try {
        const organizationId = req.appUser?.organizationId;
        const studies = await yieldStudyService.getAllStudies(organizationId);
        res.json(studies);
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        res.status(500).json({ error: message });
    }
};

export const createStudy = async (req: Request, res: Response) => {
    try {
        const organizationId = req.appUser?.organizationId;
        const study = await yieldStudyService.createStudy({ ...req.body, organizationId });
        res.status(201).json(study);
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        res.status(500).json({ error: message });
    }
};

export const updateStudy = async (req: Request, res: Response) => {
    try {
        const id = req.params.id as string;
        const organizationId = req.appUser?.organizationId;
        const study = await yieldStudyService.updateStudy(id, req.body, organizationId);
        if (study) {
            res.json(study);
        } else {
            res.status(404).json({ error: 'Study not found' });
        }
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        res.status(500).json({ error: message });
    }
};

export const deleteStudy = async (req: Request, res: Response) => {
    try {
        const id = req.params.id as string;
        const organizationId = req.appUser?.organizationId;
        const success = await yieldStudyService.deleteStudy(id, organizationId);
        if (success) {
            res.status(204).send();
        } else {
            res.status(404).json({ error: 'Study not found' });
        }
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        res.status(500).json({ error: message });
    }
};
