<?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 DiscountCreateController
{
    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_value', val::intType()->positive())
                ->key('discount_code', val::stringType()->notEmpty()->length(1, 255))
                ->assert($body);
        } catch (ValidationException $e) {
            return ResponseLib::sendFail('Validation failed: ' . $e->getFullMessage(), [], 'E_VALIDATE')->withStatus(400);
        }

        $discountValue = (int)$body['discount_value'];
        $discountCode = trim((string)$body['discount_code']);

        if ($discountCode === '') {
            return ResponseLib::sendFail('Validation failed: discount_code must not be empty', [], 'E_VALIDATE')->withStatus(400);
        }

        $discountValue = $discountValue * 100;
        if ($discountValue <= 0) {
            return ResponseLib::sendFail('Validation failed: discount_value must be greater than zero', [], 'E_VALIDATE')->withStatus(400);
        }

        try {
            $created = $this->model->create($discountValue, $discountCode);
        } catch (\PDOException $e) {
            if (($e->getCode() ?? '') === '23505') {
                return ResponseLib::sendFail('Discount code already exists', [], 'E_DUPLICATE')->withStatus(409);
            }
            return ResponseLib::sendFail('Failed to create discount: ' . $e->getMessage(), [], 'E_DATABASE')->withStatus(500);
        } catch (\Throwable $e) {
            return ResponseLib::sendFail('Failed to create discount: ' . $e->getMessage(), [], 'E_DATABASE')->withStatus(500);
        }

        return ResponseLib::sendOk($created, 'S_CREATED');
    }
}
