import { Request, Response, NextFunction } from 'express';
import { OrganizationService } from '../services/organization.service';
import { z } from 'zod';

const orgSchema = z.object({
  name: z.string().min(2),
});

const orgUpdateSchema = z.object({
  name: z.string().min(2).optional(),
  status: z.string().optional(),
});

export class OrganizationController {
  private orgService = new OrganizationService();

  public create = async (req: Request, res: Response, next: NextFunction) => {
    try {
      const data = orgSchema.parse(req.body);
      const org = await this.orgService.create(data);
      res.status(201).json(org);
    } catch(err) { next(err); }
  }

  public getAll = async (req: Request, res: Response, next: NextFunction) => {
    try {
      const orgs = await this.orgService.getAll();
      res.status(200).json(orgs);
    } catch(err) { next(err); }
  }

  public getById = async (req: Request, res: Response, next: NextFunction) => {
    try {
      const org = await this.orgService.getById(req.params.id);
      if (!org) {
        return res.status(404).json({ error: 'Organization not found' });
      }
      res.status(200).json(org);
    } catch(err) { next(err); }
  }

  public update = async (req: Request, res: Response, next: NextFunction) => {
    try {
      const data = orgUpdateSchema.parse(req.body);
      const org = await this.orgService.update(req.params.id, data);
      res.status(200).json(org);
    } catch(err) { next(err); }
  }
}
