<?php

namespace Controllers;

use Libs\ResponseLib;
use Models\DiscountModel;
use Psr\Http\Message\ServerRequestInterface;
use Respect\Validation\Exceptions\ValidationException;
use Respect\Validation\Validator as val;

class DiscountDeleteController
{
    private DiscountModel $model;

    public function __construct()
    {
        $this->model = new DiscountModel();
    }

    public function __invoke(ServerRequestInterface $request)
    {
        $body = json_decode((string)$request->getBody(), true) ?? [];

        try {
            val::key('discount_id', val::intType()->positive())
                ->assert($body);
        } catch (ValidationException $e) {
            return ResponseLib::sendFail('Validation failed: ' . $e->getFullMessage(), [], 'E_VALIDATE')->withStatus(400);
        }

        $discountId = (int)$body['discount_id'];

        try {
            $deleted = $this->model->delete($discountId);
        } catch (\Throwable $e) {
            return ResponseLib::sendFail('Failed to delete discount: ' . $e->getMessage(), [], 'E_DATABASE')->withStatus(500);
        }

        return $deleted
            ? ResponseLib::sendOk(['deleted' => true], 'S_DELETED')
            : ResponseLib::sendFail('Discount Not Found', [], 'E_DATABASE')->withStatus(204);
    }
}
