<?php

declare(strict_types=1);

namespace App\Repositories\Mypage;

use Illuminate\Support\Facades\DB;

final class MypageInfoRepository
{
    private const TABLE_MEM_INFO = 'mem_info';
    private const COL_MEM_NO     = 'mem_no';
    private const COL_CI         = 'ci';
    private const COL_CELL       = 'cell_phone';

    /**
     * mem_info 기본 정보 조회 (필요한 컬럼만)
     */
    public function findMemberCore(int $memNo): ?object
    {
        return DB::table(self::TABLE_MEM_INFO)
            ->select([
                self::COL_MEM_NO,
                self::COL_CI,
                self::COL_CELL,
            ])
            ->where(self::COL_MEM_NO, $memNo)
            ->first();
    }

    /**
     * mem_info.ci 조회
     */
    public function getMemberCi(int $memNo): string
    {
        $row = DB::table(self::TABLE_MEM_INFO)
            ->select([self::COL_CI])
            ->where(self::COL_MEM_NO, $memNo)
            ->first();

        return (string) ($row->{self::COL_CI} ?? '');
    }

    /**
     * 암호화된 휴대폰(cell) 값이 이미 존재하는지 체크
     * - excludeMemNo가 있으면 해당 회원은 제외하고 검색
     */
    public function existsEncryptedCell(string $encCell, ?int $excludeMemNo = null): bool
    {
        if ($encCell === '') return false;

        $q = DB::table(self::TABLE_MEM_INFO)
            ->where(self::COL_CELL, $encCell);

        if ($excludeMemNo !== null && $excludeMemNo > 0) {
            $q->where(self::COL_MEM_NO, '!=', $excludeMemNo);
        }

        return $q->exists();
    }

    /**
     * mem_info.cell 업데이트
     * @return int 영향을 받은 row 수
     */
    public function updateEncryptedCell(int $memNo, string $encCell): int
    {
        return DB::table(self::TABLE_MEM_INFO)
            ->where(self::COL_MEM_NO, $memNo)
            ->update([
                self::COL_CELL => $encCell,
            ]);
    }
}
