<?php

namespace Litepie\Master\Actions;

use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Litepie\Actions\Concerns\AsAction;
use Litepie\Actions\Traits\LogsActions;
use Litepie\Notification\Traits\SendNotification;
use Litepie\Master\Models\Master;


class MasterAction
{
    use AsAction;

    protected $model;
    protected $namespace = 'litepie.master.master';
    protected $eventClass = \Litepie\Master\Events\MasterAction::class;
    protected $action;
    protected $function;
    protected $request;

    public function handle(string $action, Master $master, array $request = [])
    {
        $this->action = $action;
        $this->request = $request;
        $this->model = $master;
        $this->function = Str::camel($action);
        $this->executeAction();
        return $this->model;

    }


    public function store(Master $master, array $request)
    {
        $attributes = $request;
        $attributes['user_id'] = user_id();
        $attributes['user_type'] = user_type();
        $master = $master->create($attributes);
        return $master;
    }

    public function update(Master $master, array $request)
    {
        $attributes = $request;
        $master->update($attributes);
        return $master;
    }

    public function destroy(Master $master, array $request)
    {
        $master->delete();
        return $master;
    }

    public function copy(Master $master, array $request)
    {
        $count = $request['count'] ?: 1;

        if ($count == 1) {
            $master = $master->replicate();
            $master->created_at = Carbon::now();
            $master->save();
            return $master;
        }

        for ($i = 1; $i <= $count; $i++) {
            $new = $master->replicate();
            $new->created_at = Carbon::now();
            $new->save();
        }

        return $master;
    }


}