<?php

namespace App\Modules\HR\Shifts\Repositories;

use App\Modules\HR\Shifts\Models\ShiftRotation;
use App\Modules\HR\Shifts\Models\ShiftSwapRequest;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class ShiftWorkforceRepository
{
    public function rotations(int $tenantId): Collection
    {
        return ShiftRotation::query()
            ->where('tenant_id', $tenantId)
            ->with('days.shift')
            ->orderBy('name')
            ->get();
    }

    public function swaps(int $tenantId): Collection
    {
        return ShiftSwapRequest::query()
            ->where('tenant_id', $tenantId)
            ->orderByDesc('id')
            ->limit(50)
            ->get();
    }

    public function createSwap(array $data): ShiftSwapRequest
    {
        return ShiftSwapRequest::query()->create($data);
    }

    public function lockSwap(int $tenantId, int $id): ?ShiftSwapRequest
    {
        return ShiftSwapRequest::query()
            ->where('tenant_id', $tenantId)
            ->whereKey($id)
            ->lockForUpdate()
            ->first();
    }

    public function updateSwap(ShiftSwapRequest $swap, array $data): ShiftSwapRequest
    {
        $swap->update($data);

        return $swap->fresh() ?? $swap;
    }

    public function createRotation(int $tenantId, array $data): ShiftRotation
    {
        return DB::transaction(function () use ($tenantId, $data): ShiftRotation {
            $rotation = ShiftRotation::query()->create([
                'tenant_id' => $tenantId,
                'name' => $data['name'],
                'is_active' => true,
            ]);
            $rotation->days()->createMany($data['days']);
            foreach ($data['employee_ids'] ?? [] as $employeeId) {
                DB::table('hr_shift_rotation_employees')->insert([
                    'rotation_id' => $rotation->id,
                    'employee_id' => $employeeId,
                    'starts_at' => $data['starts_at'],
                ]);
            }

            return $rotation->load('days.shift');
        });
    }
}
