<?php

namespace App\Libraries\DBMigration\Process;

use App\Entities\Equipment\PartEntity;
use CodeIgniter\Database\BaseConnection;

class PartCodeProcess implements MigrationProcessInterface
{
  private $db;
  public function __construct(BaseConnection $db)
  {
    $this->db = $db;
  }
  public function process(array $row, int $cnt): void
  {
    try {
      if (count($row) < 2) {
        throw new \Exception("{$cnt} {$row[0]}:{$row[1]} -> SKIP PARTCODE\n");
      }

      $temps = [];
      $temps['type']  = trim($row[0]);
      $temps['title']  = trim($row[1]);
      $temps['price']  = trim($row[2]);
      $temps['status'] = PartEntity::DEFAULT_STATUS;

      // INSERT
      $result = $this->db->table('partinfo')->insert($temps);

      if (!$result) {
        throw new \Exception($this->db->error()['message']);
      }

      // 방금 insert된 uid 가져오기
      $insertId = $this->db->insertID();

      // code 값 생성 (예: CPU123)
      $code = $row[0] . $insertId;

      // code 업데이트
      $this->db->table('partinfo')
        ->where('uid', $insertId)
        ->update(['code' => $code]);

      echo "{$cnt} -> {$temps['title']} ({$code}) PARTCODE 완료.\n";
    } catch (\Exception $e) {
      echo $e->getMessage();
    }
  }
}
